1use std::io::{self, Write};
38use std::ops::RangeInclusive;
39
40use base64::Engine as _;
41use base64::engine::general_purpose::STANDARD;
42
43pub const GLYPH_BLOCK: RangeInclusive<char> = '\u{100000}'..='\u{1003FF}';
45
46pub const MAX_GLYPH_PAYLOAD: usize = 32 * 1024;
49
50pub const REQUEST_GLYPH_SUPPORT: &[u8] = b"\x1b_25a1;s\x1b\\";
56
57#[derive(Debug, Clone, Copy, PartialEq)]
59pub enum GlyphPayload<'a> {
60 Vg {
65 view_box: [f32; 4],
67 layers: &'a str,
69 },
70 Glyf(&'a [u8]),
72 ColrV0(&'a [u8]),
74 ColrV1(&'a [u8]),
76}
77
78impl GlyphPayload<'_> {
79 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
92pub enum GlyphReplies {
93 #[default]
95 All,
96 Failures,
98 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#[derive(Debug, Clone, Copy, PartialEq)]
114pub struct GlyphRegistration<'a> {
115 pub codepoint: char,
117 pub payload: GlyphPayload<'a>,
119 pub replies: GlyphReplies,
121 pub options: &'a [(&'a str, &'a str)],
127}
128
129impl<'a> GlyphRegistration<'a> {
130 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
142pub 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
208pub 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
215pub 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
236pub 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}