Skip to main content

uncurses/ansi/
glyph.rs

1//! Glyph Protocol: application-defined vector glyphs over APC.
2//!
3//! ## Category
4//!
5//! This module writes the four Glyph Protocol requests: support detection
6//! (`s`), coverage queries (`q`), registration (`r`), and clearing (`c`).
7//! Replies arrive as [`Event::Glyph`](crate::event::Event::Glyph).
8//!
9//! ## APC format
10//!
11//! Every message is an APC string whose body starts with `25a1;`:
12//!
13//! ```text
14//! ESC _ 25a1 ; <verb> [ ; key=value ]* [ ; <payload> ] ESC \
15//! ```
16//!
17//! A registration carries its payload in the last field. Binary formats are
18//! base64; `vg` is printable ASCII text.
19//!
20//! ## Support detection
21//!
22//! Send [`REQUEST_GLYPH_SUPPORT`] followed by Primary DA. A supporting
23//! terminal answers `s` before the Primary DA reply. Send `q`, `r`, and `c`
24//! only after a support reply. The `uncurses-glyph` crate provides a `Probe`
25//! and a `Capabilities` record for a composed capability batch.
26//!
27//! ## Registration block
28//!
29//! Registrations target [`GLYPH_BLOCK`], `U+100000` through `U+1003FF`.
30//! A registered codepoint is an ordinary character: print it in a cell
31//! like any other text. A terminal can bind the glyph to text printed after
32//! the registration, or apply it to text already on screen. To change what
33//! is shown, register again and print the codepoint again.
34//!
35//! See the [protocol specification](https://github.com/raphamorim/rio/blob/main/specs/glyph-protocol.md).
36
37use std::io::{self, Write};
38use std::ops::RangeInclusive;
39
40use base64::Engine as _;
41use base64::engine::general_purpose::STANDARD;
42
43/// The codepoints that accept registrations: `U+100000` through `U+1003FF`.
44pub const GLYPH_BLOCK: RangeInclusive<char> = '\u{100000}'..='\u{1003FF}';
45
46/// The largest payload a terminal accepts, in bytes: decoded for the binary
47/// formats, as sent for `vg`.
48pub const MAX_GLYPH_PAYLOAD: usize = 32 * 1024;
49
50/// Request supported payload formats and capabilities:
51/// `ESC _ 25a1;s ESC \`.
52///
53/// A supporting terminal replies with
54/// [`GlyphReply::Support`](crate::event::GlyphReply::Support).
55pub const REQUEST_GLYPH_SUPPORT: &[u8] = b"\x1b_25a1;s\x1b\\";
56
57/// A glyph payload, in one of the protocol's formats.
58#[derive(Debug, Clone, Copy, PartialEq)]
59pub enum GlyphPayload<'a> {
60    /// `fmt=vg`: SVG path layers as text.
61    ///
62    /// `layers` is one to 128 `|`-separated layers, such as
63    /// `fill=nonzero,fg:M2 2H22V22H2Z`. It must be printable ASCII.
64    Vg {
65        /// The viewBox: `x`, `y`, width, and height. The y axis points down.
66        view_box: [f32; 4],
67        /// The layer text, sent unchanged.
68        layers: &'a str,
69    },
70    /// `fmt=glyf`: an OpenType simple-glyph record, without hinting.
71    Glyf(&'a [u8]),
72    /// `fmt=colrv0`: a `COLR` v0 and `CPAL` container.
73    ColrV0(&'a [u8]),
74    /// `fmt=colrv1`: a `COLR` v1 container.
75    ColrV1(&'a [u8]),
76}
77
78impl GlyphPayload<'_> {
79    /// The format name on the wire, as listed in a support reply.
80    pub const fn format(&self) -> &'static str {
81        match self {
82            Self::Vg { .. } => "vg",
83            Self::Glyf(_) => "glyf",
84            Self::ColrV0(_) => "colrv0",
85            Self::ColrV1(_) => "colrv1",
86        }
87    }
88}
89
90/// Which replies a registration or clear request asks for.
91#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
92pub enum GlyphReplies {
93    /// Reply to success and failure (`reply=1`, the protocol default).
94    #[default]
95    All,
96    /// Reply to failure only (`reply=2`).
97    Failures,
98    /// Send no reply (`reply=0`).
99    Silent,
100}
101
102impl GlyphReplies {
103    fn param(self) -> Option<&'static str> {
104        match self {
105            Self::All => None,
106            Self::Failures => Some("2"),
107            Self::Silent => Some("0"),
108        }
109    }
110}
111
112/// A registration request for one codepoint.
113#[derive(Debug, Clone, Copy, PartialEq)]
114pub struct GlyphRegistration<'a> {
115    /// The target codepoint. Terminals accept codepoints in [`GLYPH_BLOCK`].
116    pub codepoint: char,
117    /// The glyph payload and its format.
118    pub payload: GlyphPayload<'a>,
119    /// Which replies to request.
120    pub replies: GlyphReplies,
121    /// Placement keys, such as `("width", "2")`, `("fit", "cover")`, or
122    /// `("align", "center,baseline")`, written in order.
123    ///
124    /// Keys are lowercase ASCII letters. Values are printable ASCII without
125    /// `;`. The writer sets `cp`, `fmt`, `vb`, and `reply` itself.
126    pub options: &'a [(&'a str, &'a str)],
127}
128
129impl<'a> GlyphRegistration<'a> {
130    /// Create a registration that requests every reply and sets no
131    /// placement keys.
132    pub const fn new(codepoint: char, payload: GlyphPayload<'a>) -> Self {
133        Self {
134            codepoint,
135            payload,
136            replies: GlyphReplies::All,
137            options: &[],
138        }
139    }
140}
141
142/// Write a registration request.
143///
144/// Binary payloads are base64-encoded. The writer checks the framing before
145/// any output: `vg` text and option values must be printable ASCII without
146/// `;`, option keys must be lowercase ASCII letters other than the keys the
147/// writer sets, and the payload must fit [`MAX_GLYPH_PAYLOAD`]. The terminal
148/// checks the codepoint and the payload content, and replies with a reason.
149pub fn write_glyph_register<W: Write>(
150    w: &mut W,
151    registration: &GlyphRegistration<'_>,
152) -> io::Result<()> {
153    let payload = match registration.payload {
154        GlyphPayload::Vg { layers, .. } => {
155            check_text(layers, "vg layers")?;
156            layers.as_bytes()
157        }
158        GlyphPayload::Glyf(bytes) | GlyphPayload::ColrV0(bytes) | GlyphPayload::ColrV1(bytes) => {
159            bytes
160        }
161    };
162    if payload.len() > MAX_GLYPH_PAYLOAD {
163        return Err(invalid("glyph payload exceeds 32 KiB"));
164    }
165    if let GlyphPayload::Vg { view_box, .. } = registration.payload
166        && !view_box.iter().all(|v| v.is_finite())
167    {
168        return Err(invalid("glyph view box must be finite"));
169    }
170    for &(key, value) in registration.options {
171        if key.is_empty()
172            || !key.bytes().all(|b| b.is_ascii_lowercase())
173            || matches!(key, "cp" | "fmt" | "vb" | "reply")
174        {
175            return Err(invalid("invalid glyph option key"));
176        }
177        check_text(value, "glyph option value")?;
178    }
179
180    let mut sequence = format!(
181        "\x1b_25a1;r;cp={:x};fmt={}",
182        u32::from(registration.codepoint),
183        registration.payload.format()
184    );
185    if let GlyphPayload::Vg {
186        view_box: [x, y, width, height],
187        ..
188    } = registration.payload
189    {
190        sequence.push_str(&format!(";vb={x},{y},{width},{height}"));
191    }
192    if let Some(reply) = registration.replies.param() {
193        sequence.push_str(";reply=");
194        sequence.push_str(reply);
195    }
196    for &(key, value) in registration.options {
197        sequence.push_str(&format!(";{key}={value}"));
198    }
199    sequence.push(';');
200    match registration.payload {
201        GlyphPayload::Vg { layers, .. } => sequence.push_str(layers),
202        _ => STANDARD.encode_string(payload, &mut sequence),
203    }
204    sequence.push_str("\x1b\\");
205    w.write_all(sequence.as_bytes())
206}
207
208/// Write a coverage query for one codepoint: `ESC _ 25a1;q;cp=<hex> ESC \`.
209///
210/// Any Unicode scalar value is valid, inside or outside [`GLYPH_BLOCK`].
211pub fn write_glyph_query<W: Write>(w: &mut W, codepoint: char) -> io::Result<()> {
212    write!(w, "\x1b_25a1;q;cp={:x}\x1b\\", u32::from(codepoint))
213}
214
215/// Write a coverage query for one grapheme cluster:
216/// `ESC _ 25a1;q;grapheme=<hex>,<hex>,... ESC \`.
217///
218/// Send this only when the support reply lists the `grapheme` capability.
219/// The terminal answers for exactly these scalar values. The writer returns
220/// [`io::ErrorKind::InvalidInput`] for counts outside 1 to 32, before any output.
221pub fn write_glyph_query_grapheme<W: Write>(w: &mut W, cluster: &str) -> io::Result<()> {
222    if !(1..=32).contains(&cluster.chars().count()) {
223        return Err(invalid("glyph query requires one to 32 scalar values"));
224    }
225    let mut sequence = String::from("\x1b_25a1;q;grapheme=");
226    for (i, ch) in cluster.chars().enumerate() {
227        if i > 0 {
228            sequence.push(',');
229        }
230        sequence.push_str(&format!("{:x}", u32::from(ch)));
231    }
232    sequence.push_str("\x1b\\");
233    w.write_all(sequence.as_bytes())
234}
235
236/// Write a clear request: `ESC _ 25a1;c[;cp=<hex>][;reply=<n>] ESC \`.
237///
238/// `None` clears every registration in the session.
239pub fn write_glyph_clear<W: Write>(
240    w: &mut W,
241    codepoint: Option<char>,
242    replies: GlyphReplies,
243) -> io::Result<()> {
244    w.write_all(b"\x1b_25a1;c")?;
245    if let Some(codepoint) = codepoint {
246        write!(w, ";cp={:x}", u32::from(codepoint))?;
247    }
248    if let Some(reply) = replies.param() {
249        write!(w, ";reply={reply}")?;
250    }
251    w.write_all(b"\x1b\\")
252}
253
254fn check_text(text: &str, what: &str) -> io::Result<()> {
255    if text
256        .bytes()
257        .all(|b| (0x20..=0x7e).contains(&b) && b != b';')
258    {
259        Ok(())
260    } else {
261        Err(invalid(&format!(
262            "{what} must be printable ASCII without ';'"
263        )))
264    }
265}
266
267fn invalid(message: &str) -> io::Error {
268    io::Error::new(io::ErrorKind::InvalidInput, message.to_owned())
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274
275    fn written(f: impl FnOnce(&mut Vec<u8>) -> io::Result<()>) -> String {
276        let mut buf = Vec::new();
277        f(&mut buf).unwrap();
278        String::from_utf8(buf).unwrap()
279    }
280
281    #[test]
282    fn register_writes_keys_then_payload_last() {
283        let vg = GlyphRegistration {
284            replies: GlyphReplies::Failures,
285            options: &[("fit", "cover"), ("align", "start,end")],
286            ..GlyphRegistration::new(
287                '\u{100000}',
288                GlyphPayload::Vg {
289                    view_box: [0.0, 0.0, 24.0, 1.5],
290                    layers: "fill=nonzero,fg:M0 0H24V1.5Z",
291                },
292            )
293        };
294        assert_eq!(
295            written(|w| write_glyph_register(w, &vg)),
296            "\x1b_25a1;r;cp=100000;fmt=vg;vb=0,0,24,1.5;reply=2;fit=cover;align=start,end;\
297             fill=nonzero,fg:M0 0H24V1.5Z\x1b\\"
298        );
299
300        let glyf = GlyphRegistration::new('\u{1003ff}', GlyphPayload::Glyf(&[0xff, 0x00]));
301        assert_eq!(
302            written(|w| write_glyph_register(w, &glyf)),
303            "\x1b_25a1;r;cp=1003ff;fmt=glyf;/wA=\x1b\\"
304        );
305    }
306
307    #[test]
308    fn register_rejects_input_that_breaks_framing() {
309        let vg = |layers| GlyphPayload::Vg {
310            view_box: [0.0, 0.0, 1.0, 1.0],
311            layers,
312        };
313        let big = vec![0; MAX_GLYPH_PAYLOAD + 1];
314        let cases = [
315            GlyphRegistration::new('\u{100000}', vg("fill=nonzero,fg:M0 0;")),
316            GlyphRegistration::new('\u{100000}', vg("fill=nonzero,fg:M0 0\x1b\\")),
317            GlyphRegistration::new('\u{100000}', GlyphPayload::ColrV1(&big)),
318            GlyphRegistration::new(
319                '\u{100000}',
320                GlyphPayload::Vg {
321                    view_box: [0.0, 0.0, f32::NAN, 1.0],
322                    layers: "",
323                },
324            ),
325            GlyphRegistration {
326                options: &[("reply", "1")],
327                ..GlyphRegistration::new('\u{100000}', GlyphPayload::Glyf(&[]))
328            },
329            GlyphRegistration {
330                options: &[("width", "2;x")],
331                ..GlyphRegistration::new('\u{100000}', GlyphPayload::Glyf(&[]))
332            },
333        ];
334        for case in cases {
335            let mut buf = Vec::new();
336            let err = write_glyph_register(&mut buf, &case).unwrap_err();
337            assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{case:?}");
338            assert!(buf.is_empty());
339        }
340    }
341
342    #[test]
343    fn query_and_clear_requests() {
344        assert_eq!(
345            written(|w| write_glyph_query(w, '\u{e0a0}')),
346            "\x1b_25a1;q;cp=e0a0\x1b\\"
347        );
348        assert_eq!(
349            written(|w| write_glyph_query_grapheme(w, "👨\u{200d}👩")),
350            "\x1b_25a1;q;grapheme=1f468,200d,1f469\x1b\\"
351        );
352        assert_eq!(
353            written(|w| write_glyph_clear(w, None, GlyphReplies::All)),
354            "\x1b_25a1;c\x1b\\"
355        );
356        assert_eq!(
357            written(|w| write_glyph_clear(w, Some('\u{100001}'), GlyphReplies::Silent)),
358            "\x1b_25a1;c;cp=100001;reply=0\x1b\\"
359        );
360    }
361
362    #[test]
363    fn grapheme_query_checks_scalar_count_before_output() {
364        let cluster = "\u{1f600}".repeat(32);
365        assert_eq!(
366            written(|w| write_glyph_query_grapheme(w, &cluster)),
367            format!("\x1b_25a1;q;grapheme={}1f600\x1b\\", "1f600,".repeat(31))
368        );
369        for cluster in ["".to_owned(), "a".repeat(33)] {
370            let mut out = Vec::new();
371            let error = write_glyph_query_grapheme(&mut out, &cluster).unwrap_err();
372            assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
373            assert!(out.is_empty());
374        }
375    }
376}