uncurses/terminal/size.rs
1//! Terminal window-size detection.
2//!
3//! [`get_window_size`] queries the operating system for the visible terminal
4//! dimensions. Sizes are reported as [`Winsize`]: rows and columns in terminal
5//! cells, plus pixel dimensions when the platform exposes them.
6
7use std::io;
8
9#[cfg(unix)]
10use std::os::fd::{AsFd, AsRawFd};
11#[cfg(windows)]
12use std::os::windows::io::{AsHandle, AsRawHandle};
13#[cfg(windows)]
14use windows_sys::Win32::Foundation::HANDLE;
15
16/// Terminal dimensions in cells and pixels.
17///
18/// `row` and `col` are the cell dimensions used for terminal layout. `xpixel`
19/// and `ypixel` are optional pixel dimensions; they are `0` when the platform
20/// or terminal does not report pixel size.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub struct Winsize {
23 /// Number of rows (height in cells).
24 pub row: u16,
25 /// Number of columns (width in cells).
26 pub col: u16,
27 /// Width in pixels, or `0` when unknown.
28 pub xpixel: u16,
29 /// Height in pixels, or `0` when unknown.
30 pub ypixel: u16,
31}
32
33impl Default for Winsize {
34 /// Return the conventional fallback size of 80 columns by 24 rows.
35 ///
36 /// Pixel dimensions are unknown and set to `0`.
37 fn default() -> Self {
38 Self {
39 row: 24,
40 col: 80,
41 xpixel: 0,
42 ypixel: 0,
43 }
44 }
45}
46
47impl Winsize {
48 /// Estimate one cell's pixel size from the terminal's window dimensions.
49 ///
50 /// This divides the pixel width and height by the number of columns and
51 /// rows. It returns `None` when a dimension is zero or unknown. The
52 /// result is rounded down and may be smaller than the actual cell size
53 /// when the window has padding.
54 ///
55 /// Use [`crate::program::Program::request_cell_pixel_size`] when you need
56 /// the size reported directly by the terminal.
57 pub fn estimated_cell_pixel_size(self) -> Option<crate::layout::Size> {
58 if self.col == 0 || self.row == 0 || self.xpixel == 0 || self.ypixel == 0 {
59 return None;
60 }
61 let size = crate::layout::Size::new(self.xpixel / self.col, self.ypixel / self.row);
62 (size.width > 0 && size.height > 0).then_some(size)
63 }
64}
65
66impl From<Winsize> for (u16, u16) {
67 /// Convert to a `(width, height)` cell pair.
68 ///
69 /// The returned tuple is `(col, row)`. Pixel fields are dropped.
70 fn from(ws: Winsize) -> Self {
71 (ws.col, ws.row)
72 }
73}
74
75/// Query the terminal size attached to `fd`.
76///
77/// This calls `TIOCGWINSZ` and returns the kernel-provided row, column, and
78/// pixel fields.
79///
80/// # Parameters
81///
82/// * `fd` — descriptor to query.
83///
84/// # Returns
85///
86/// The current [`Winsize`].
87///
88/// # Errors
89///
90/// Returns the OS error if `ioctl` fails, for example because `fd` is not a
91/// terminal.
92///
93/// # Panics
94///
95/// This function does not intentionally panic.
96#[cfg(unix)]
97pub fn get_window_size<F: AsFd>(fd: F) -> io::Result<Winsize> {
98 let mut ws: libc::winsize = unsafe { std::mem::zeroed() };
99 let ret = unsafe { libc::ioctl(fd.as_fd().as_raw_fd(), libc::TIOCGWINSZ, &mut ws) };
100 if ret < 0 {
101 return Err(io::Error::last_os_error());
102 }
103 Ok(Winsize {
104 row: ws.ws_row,
105 col: ws.ws_col,
106 xpixel: ws.ws_xpixel,
107 ypixel: ws.ws_ypixel,
108 })
109}
110
111/// Query the visible console window size attached to `h`.
112///
113/// Pixel dimensions are unavailable on this platform and are returned as `0`.
114///
115/// # Parameters
116///
117/// * `h` — console screen-buffer handle to query.
118///
119/// # Returns
120///
121/// The current [`Winsize`] in cells.
122///
123/// # Errors
124///
125/// Returns the OS error if `GetConsoleScreenBufferInfo` fails, for example
126/// because `h` is not a console output handle.
127///
128/// # Panics
129///
130/// This function does not intentionally panic.
131#[cfg(windows)]
132pub fn get_window_size<H: AsHandle>(h: H) -> io::Result<Winsize> {
133 use windows_sys::Win32::System::Console::{
134 CONSOLE_SCREEN_BUFFER_INFO, GetConsoleScreenBufferInfo,
135 };
136
137 let handle = h.as_handle().as_raw_handle() as HANDLE;
138 let mut info: CONSOLE_SCREEN_BUFFER_INFO = unsafe { std::mem::zeroed() };
139 if unsafe { GetConsoleScreenBufferInfo(handle, &mut info) } == 0 {
140 return Err(io::Error::last_os_error());
141 }
142 let col = (info.srWindow.Right - info.srWindow.Left + 1).max(0) as u16;
143 let row = (info.srWindow.Bottom - info.srWindow.Top + 1).max(0) as u16;
144 Ok(Winsize {
145 row,
146 col,
147 xpixel: 0,
148 ypixel: 0,
149 })
150}
151
152#[cfg(not(any(unix, windows)))]
153/// Query the terminal size on an unsupported platform.
154///
155/// Always returns [`io::ErrorKind::Unsupported`].
156pub fn get_window_size<T>(_: T) -> io::Result<Winsize> {
157 Err(io::Error::new(
158 io::ErrorKind::Unsupported,
159 "get_window_size is not implemented for this platform",
160 ))
161}
162
163#[cfg(test)]
164mod tests {
165 use super::*;
166
167 #[test]
168 fn default_size_is_80x24() {
169 let s = Winsize::default();
170 assert_eq!(s.col, 80);
171 assert_eq!(s.row, 24);
172 }
173
174 #[test]
175 fn estimated_cell_pixel_size_divides_window_dimensions() {
176 let size = Winsize {
177 row: 30,
178 col: 100,
179 xpixel: 1500,
180 ypixel: 900,
181 };
182 assert_eq!(
183 size.estimated_cell_pixel_size(),
184 Some(crate::layout::Size::new(15, 30))
185 );
186 }
187
188 #[test]
189 fn estimated_cell_pixel_size_returns_none_for_unknown_or_zero_dimensions() {
190 for size in [
191 Winsize::default(),
192 Winsize {
193 row: 0,
194 col: 100,
195 xpixel: 1500,
196 ypixel: 900,
197 },
198 Winsize {
199 row: 30,
200 col: 0,
201 xpixel: 1500,
202 ypixel: 900,
203 },
204 Winsize {
205 row: 30,
206 col: 100,
207 xpixel: 1,
208 ypixel: 900,
209 },
210 Winsize {
211 row: 30,
212 col: 100,
213 xpixel: 1500,
214 ypixel: 1,
215 },
216 ] {
217 assert_eq!(size.estimated_cell_pixel_size(), None, "{size:?}");
218 }
219 }
220}