uncurses/ansi/graphics.rs
1//! Inline graphics encoders for DCS and APC image protocols.
2//!
3//! ## Category
4//!
5//! This module frames image payloads as either Sixel DCS strings or APC graphics
6//! strings. It does not inspect, compress, or validate the image payload itself.
7//!
8//! ## String-control framing
9//!
10//! Both writers use 7-bit string controls terminated by `ST` (`ESC \\`):
11//!
12//! ```text
13//! ESC P ... q payload ESC \\ DCS Sixel
14//! ESC _ G opts ; payload ESC \\ APC graphics
15//! ──┬── ──┬──
16//! intro terminator
17//! ```
18//!
19//! ## Mode interaction
20//!
21//! Inline graphics are not toggled by a mode in this module. Terminals may impose
22//! their own size, capability, or security policy on received payloads.
23
24use std::io::{self, Write};
25
26mod diacritics;
27pub use diacritics::KITTY_PLACEHOLDER_DIACRITICS;
28
29/// Frame a Sixel payload as `ESC P <p1> ; <p2> [;<p3>] q <payload> ESC \`.
30///
31/// `p1` and `p2` are omitted when negative, while their semicolon separator remains. `p3` is emitted only when greater than zero. `payload` is copied verbatim between the `q` final byte and `ST`.
32pub fn write_sixel<W: Write>(
33 w: &mut W,
34 p1: i32,
35 p2: i32,
36 p3: i32,
37 payload: &[u8],
38) -> io::Result<()> {
39 w.write_all(b"\x1bP")?;
40 if p1 >= 0 {
41 write!(w, "{p1}")?;
42 }
43 w.write_all(b";")?;
44 if p2 >= 0 {
45 write!(w, "{p2}")?;
46 }
47 if p3 > 0 {
48 write!(w, ";{p3}")?;
49 }
50 w.write_all(b"q")?;
51 w.write_all(payload)?;
52 w.write_all(b"\x1b\\")
53}
54
55/// Frame a graphics payload as `ESC _ G <options> [;<payload>] ESC \`.
56///
57/// `options` are emitted verbatim and joined with commas. The semicolon before `payload` is omitted when `payload` is empty.
58pub fn write_kitty_graphics<W: Write>(
59 w: &mut W,
60 options: &[&str],
61 payload: &[u8],
62) -> io::Result<()> {
63 w.write_all(b"\x1b_G")?;
64 for (i, opt) in options.iter().enumerate() {
65 if i > 0 {
66 w.write_all(b",")?;
67 }
68 w.write_all(opt.as_bytes())?;
69 }
70 if !payload.is_empty() {
71 w.write_all(b";")?;
72 w.write_all(payload)?;
73 }
74 w.write_all(b"\x1b\\")
75}
76
77#[cfg(test)]
78mod tests {
79 use super::*;
80
81 #[test]
82 fn test_sixel_minimal() {
83 let mut buf = Vec::new();
84 write_sixel(&mut buf, 0, 1, 0, b"#0;2;0;0;0").unwrap();
85 assert_eq!(buf, b"\x1bP0;1q#0;2;0;0;0\x1b\\");
86 }
87
88 #[test]
89 fn test_kitty_graphics() {
90 let mut buf = Vec::new();
91 write_kitty_graphics(&mut buf, &["a=T", "f=32", "s=10", "v=20"], b"AAAA").unwrap();
92 assert_eq!(buf, b"\x1b_Ga=T,f=32,s=10,v=20;AAAA\x1b\\");
93 }
94}