Skip to main content

uncurses/ansi/
text_sizing.rs

1//! Kitty OSC 66 text sizing.
2//!
3//! [`write_sized_text`] encodes text at the current cursor position.
4//! Cursor placement and frame state belong to the screen's renderer.
5//!
6//! See <https://sw.kovidgoyal.net/kitty/text-sizing-protocol/>.
7
8use std::io::{self, Write};
9
10use crate::layout::Size;
11
12/// Geometry and fractional font size for one Kitty OSC 66 block.
13///
14/// An explicit block occupies `scale * width` columns and `scale` rows.
15/// Fractional scale changes the font inside that footprint.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub struct TextSizing {
18    /// Overall scale, from 1 through 7.
19    pub scale: u8,
20    /// Width before scaling, from 0 through 7.
21    ///
22    /// Zero asks the terminal to segment and measure the text.
23    /// Screen placements use an explicit width from 1 through 7.
24    pub width: u8,
25    /// Fractional scale numerator, from 0 through 15.
26    pub numerator: u8,
27    /// Fractional scale denominator, from 0 through 15.
28    /// When nonzero, it must exceed `numerator`.
29    pub denominator: u8,
30    /// Vertical alignment: 0 for top, 1 for bottom, 2 for center.
31    pub vertical: u8,
32    /// Horizontal alignment: 0 for left, 1 for right, 2 for center.
33    pub horizontal: u8,
34}
35
36impl Default for TextSizing {
37    fn default() -> Self {
38        Self {
39            scale: 1,
40            width: 1,
41            numerator: 0,
42            denominator: 0,
43            vertical: 0,
44            horizontal: 0,
45        }
46    }
47}
48
49impl TextSizing {
50    fn validate(self) -> io::Result<()> {
51        if !(1..=7).contains(&self.scale)
52            || self.width > 7
53            || self.numerator > 15
54            || self.denominator > 15
55            || (self.denominator != 0 && self.denominator <= self.numerator)
56            || self.vertical > 2
57            || self.horizontal > 2
58        {
59            return Err(io::Error::new(
60                io::ErrorKind::InvalidInput,
61                "invalid text sizing metadata",
62            ));
63        }
64        Ok(())
65    }
66
67    /// Validate an explicit width and return its exact footprint.
68    ///
69    /// Automatic width (`width = 0`) returns `InvalidInput`.
70    pub fn size(self) -> io::Result<Size> {
71        self.validate()?;
72        if self.width == 0 {
73            return Err(io::Error::new(
74                io::ErrorKind::InvalidInput,
75                "sized text blocks require an explicit width",
76            ));
77        }
78        Ok(Size::new(
79            u16::from(self.scale) * u16::from(self.width),
80            u16::from(self.scale),
81        ))
82    }
83}
84
85pub(crate) fn validate_text(text: &str) -> io::Result<()> {
86    if text.len() > 4096 || text.chars().any(char::is_control) {
87        return Err(io::Error::new(
88            io::ErrorKind::InvalidInput,
89            "sized text must be escape-code safe and at most 4096 UTF-8 bytes",
90        ));
91    }
92    Ok(())
93}
94
95/// Write one OSC 66 sequence at the current cursor position.
96///
97/// Text must be escape-code-safe UTF-8 with at most 4096 bytes.
98/// Empty text encodes an explicit space so the terminal advances the cursor.
99/// A leading combining character can join existing terminal content; screen
100/// placements require text that stays within their declared footprint.
101///
102/// Invalid metadata or text returns `InvalidInput` before any bytes are written.
103/// Writer errors are propagated. This function does not flush.
104pub fn write_sized_text<W: Write + ?Sized>(
105    out: &mut W,
106    text: &str,
107    sizing: TextSizing,
108) -> io::Result<()> {
109    sizing.validate()?;
110    validate_text(text)?;
111    write!(
112        out,
113        "\x1b]66;s={}:w={}:n={}:d={}:v={}:h={};{}\x1b\\",
114        sizing.scale,
115        sizing.width,
116        sizing.numerator,
117        sizing.denominator,
118        sizing.vertical,
119        sizing.horizontal,
120        if text.is_empty() { " " } else { text },
121    )
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127
128    #[test]
129    fn encodes_explicit_and_automatic_width_without_cursor_moves() {
130        for width in [0, 1, 7] {
131            let mut bytes = Vec::new();
132            write_sized_text(
133                &mut bytes,
134                "ab",
135                TextSizing {
136                    width,
137                    ..Default::default()
138                },
139            )
140            .unwrap();
141            assert_eq!(
142                bytes,
143                format!("\x1b]66;s=1:w={width}:n=0:d=0:v=0:h=0;ab\x1b\\").as_bytes()
144            );
145        }
146    }
147
148    #[test]
149    fn invalid_input_preserves_output() {
150        for (text, sizing) in [
151            ("\x07", TextSizing::default()),
152            (
153                "valid",
154                TextSizing {
155                    scale: 8,
156                    ..Default::default()
157                },
158            ),
159            (
160                "valid",
161                TextSizing {
162                    numerator: 2,
163                    denominator: 1,
164                    ..Default::default()
165                },
166            ),
167        ] {
168            let mut bytes = b"prefix".to_vec();
169            assert!(write_sized_text(&mut bytes, text, sizing).is_err());
170            assert_eq!(bytes, b"prefix");
171        }
172    }
173
174    #[test]
175    fn empty_text_encodes_a_space() {
176        let mut bytes = Vec::new();
177        write_sized_text(&mut bytes, "", TextSizing::default()).unwrap();
178        assert_eq!(bytes, b"\x1b]66;s=1:w=1:n=0:d=0:v=0:h=0; \x1b\\");
179    }
180}