Skip to main content

fontoxide_ttlib/tables/
svg.rs

1//! `SVG `: Scalable Vector Graphics table (`fontTools.ttLib.tables.S_V_G_`).
2
3use std::collections::HashMap;
4use std::io::{Read, Write};
5
6use fontoxide_misc::Tag;
7use fontoxide_misc::py;
8use fontoxide_misc::xml_reader::Element;
9use fontoxide_misc::xml_writer::XmlWriter;
10
11use crate::binary::{Reader, WriteBytes, fit};
12use crate::table::{Table, TableType, TableXml};
13use crate::tables::eblc::{clip, required_attr};
14use crate::{Error, Font, Result};
15
16const HEADER_SIZE: u64 = 10;
17const ENTRY_SIZE: u64 = 12;
18
19/// An SVG document (`SVGDocument`).
20#[derive(Debug, Clone, PartialEq, Eq, Default)]
21pub struct SvgDocument {
22	/// The document (`data`).
23	pub data: String,
24	/// `startGlyphID`.
25	pub start_glyph_id: u16,
26	/// `endGlyphID`.
27	pub end_glyph_id: u16,
28	/// Whether it is compressed in the font (`compressed`).
29	pub compressed: bool,
30}
31
32/// Scalable Vector Graphics table (`table_S_V_G_`).
33///
34/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/svg>.
35#[derive(Debug, Clone, PartialEq, Eq, Default)]
36pub struct Svg {
37	/// The documents (`docList`), if set.
38	pub doc_list: Option<Vec<SvgDocument>>,
39	/// Compress all documents when compiling (`compressed`).
40	pub compressed: bool,
41}
42
43fn no_doc_list() -> Error {
44	Error::ttlib("AttributeError: 'table_S_V_G_' object has no attribute 'docList'")
45}
46
47fn slice_of(data: &[u8], start: u64, n: u64) -> Result<Reader<'_>> {
48	let slice = clip(data, start, start.saturating_add(n));
49	if (slice.len() as u64) < n {
50		return Err(Error::Struct(format!(
51			"unpack requires a buffer of {n} bytes"
52		)));
53	}
54	Ok(Reader::new(slice))
55}
56
57/// `GzipFile.read`, which reads all the members of the file.
58fn gunzip(data: &[u8]) -> Result<Vec<u8>> {
59	let mut out = Vec::new();
60	flate2::read::MultiGzDecoder::new(data)
61		.read_to_end(&mut out)
62		.map_err(|e| Error::ttlib(format!("gzip error: {e}")))?;
63	Ok(out)
64}
65
66/// `GzipFile(None, "w", fileobj, mtime=0)` with the default compression level.
67///
68/// LENIENT(L25): the header is the same as fontTools', but the deflate stream
69/// comes from another implementation than zlib.
70fn gzip(data: &[u8]) -> Vec<u8> {
71	let mut encoder = flate2::GzBuilder::new()
72		.mtime(0)
73		.operating_system(255)
74		.write(Vec::new(), flate2::Compression::new(9));
75	// Writing to a Vec cannot fail.
76	let _ = encoder.write_all(data);
77	encoder.finish().unwrap_or_default()
78}
79
80const GZIP_MAGIC: &[u8] = b"\x1f\x8b";
81
82impl TableType for Svg {
83	const TAG: Tag = Tag::new(b"SVG ");
84
85	fn decompile(data: &[u8], _font: &mut Font) -> Result<Self> {
86		let mut r = slice_of(data, 0, HEADER_SIZE)?;
87		let version = r.u16()?;
88		let offset = u64::from(r.u32()?);
89		if version != 0 {
90			log::warn!("Unknown SVG table version '{version}'. Decompiling as version 0.");
91		}
92		let num_entries = slice_of(data, offset, 2)?.u16()?;
93		let entries_at = offset.saturating_add(2);
94		let mut docs = Vec::with_capacity(usize::from(num_entries));
95		let mut entries = Vec::with_capacity(usize::from(num_entries));
96		for i in 0..u64::from(num_entries) {
97			let mut r = slice_of(data, entries_at.saturating_add(i * ENTRY_SIZE), ENTRY_SIZE)?;
98			entries.push((r.u16()?, r.u16()?, r.u32()?, r.u32()?));
99		}
100		for (start_glyph_id, end_glyph_id, doc_offset, doc_length) in entries {
101			let start = u64::from(doc_offset) + offset;
102			let doc = clip(data, start, start + u64::from(doc_length));
103			let compressed = doc.starts_with(GZIP_MAGIC);
104			let doc = if compressed {
105				gunzip(doc)?
106			} else {
107				doc.to_vec()
108			};
109			let data = String::from_utf8(doc)
110				.map_err(|e| Error::ttlib(format!("UnicodeDecodeError: {e}")))?;
111			docs.push(SvgDocument {
112				data,
113				start_glyph_id,
114				end_glyph_id,
115				compressed,
116			});
117		}
118		Ok(Svg {
119			doc_list: Some(docs),
120			compressed: false,
121		})
122	}
123}
124
125impl Table for Svg {
126	fn tag(&self) -> Tag {
127		Self::TAG
128	}
129
130	fn compile(&mut self, _font: &mut Font) -> Result<Vec<u8>> {
131		let docs = self.doc_list.as_ref().ok_or_else(no_doc_list)?;
132		let num_entries: u16 = fit(docs.len(), "numEntries")?;
133		let mut out = Vec::new();
134		out.put_u16(0);
135		out.put_u32(HEADER_SIZE as u32);
136		out.put_u32(0);
137		out.put_u16(num_entries);
138		let mut cur_offset = 2 + ENTRY_SIZE * u64::from(num_entries);
139		let mut seen = HashMap::<Vec<u8>, u32>::new();
140		let mut doc_data = Vec::new();
141		for doc in docs {
142			let mut bytes = doc.data.clone().into_bytes();
143			if (self.compressed || doc.compressed) && !bytes.starts_with(GZIP_MAGIC) {
144				let gzipped = gzip(&bytes);
145				if gzipped.len() < bytes.len() {
146					bytes = gzipped;
147				}
148			}
149			let length: u32 = fit(bytes.len(), "svgDocLength")?;
150			let offset = match seen.get(&bytes) {
151				Some(&offset) => offset,
152				None => {
153					let offset: u32 = fit(cur_offset, "svgDocOffset")?;
154					cur_offset += bytes.len() as u64;
155					doc_data.extend_from_slice(&bytes);
156					seen.insert(bytes, offset);
157					offset
158				}
159			};
160			out.put_u16(doc.start_glyph_id);
161			out.put_u16(doc.end_glyph_id);
162			out.put_u32(offset);
163			out.put_u32(length);
164		}
165		out.extend(doc_data);
166		Ok(out)
167	}
168
169	fn clone_table(&self) -> Box<dyn Table> {
170		Box::new(self.clone())
171	}
172
173	fn remap_glyphs(&mut self, _f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
174		// The documents are subset with the glyphs, which sets the IDs.
175		Ok(())
176	}
177}
178
179impl TableXml for Svg {
180	fn to_xml(&self, writer: &mut XmlWriter, _font: &mut Font) -> Result<()> {
181		for doc in self.doc_list.as_ref().ok_or_else(no_doc_list)? {
182			if doc.compressed {
183				writer.begintag(
184					"svgDoc",
185					&[
186						("startGlyphID", &doc.start_glyph_id),
187						("endGlyphID", &doc.end_glyph_id),
188						("compressed", &1),
189					],
190				);
191			} else {
192				writer.begintag(
193					"svgDoc",
194					&[
195						("startGlyphID", &doc.start_glyph_id),
196						("endGlyphID", &doc.end_glyph_id),
197					],
198				);
199			}
200			writer.newline();
201			writer.writecdata(&doc.data);
202			writer.newline();
203			writer.endtag("svgDoc");
204			writer.newline();
205		}
206		Ok(())
207	}
208
209	fn from_xml(&mut self, element: &Element, _font: &mut Font) -> Result<()> {
210		if element.name != "svgDoc" {
211			log::warn!("Unknown {} {:?}", element.name, element.text());
212			return Ok(());
213		}
214		let int = |name: &str| -> Result<u16> {
215			let value = required_attr(element, name)?;
216			let value = py::parse_int(value).ok_or_else(|| {
217				Error::value(format!("invalid literal for int() with base 10: '{value}'"))
218			})?;
219			fit(value, name)
220		};
221		let compressed = match element.attr("compressed") {
222			Some(value) => {
223				crate::sstruct::eval(value)?
224					.as_int()
225					.ok_or_else(|| Error::value("invalid value for compressed"))?
226					!= 0
227			}
228			None => false,
229		};
230		let doc = SvgDocument {
231			data: py::strip(&element.text()).to_owned(),
232			start_glyph_id: int("startGlyphID")?,
233			end_glyph_id: int("endGlyphID")?,
234			compressed,
235		};
236		self.doc_list.get_or_insert_default().push(doc);
237		Ok(())
238	}
239}
240
241#[cfg(test)]
242mod tests {
243	use fontoxide_misc::xml_reader;
244
245	use super::*;
246
247	const DOC0: &str = "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" version=\"1.1\"><defs><rect x=\"100\" y=\"-200\" width=\"300\" height=\"400\" id=\"p1\"/></defs><g id=\"glyph1\"><use xlink:href=\"#p1\" fill=\"#red\"/></g><g id=\"glyph2\"><use xlink:href=\"#p1\" fill=\"#blue\"/></g><g id=\"glyph4\"><use xlink:href=\"#p1\" fill=\"#green\"/></g></svg>";
248	const DOC1: &str = "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"><g id=\"glyph3\"><path d=\"M0,0 L100,0 L50,100 Z\" fill=\"#red\"/><path d=\"M10,10 L110,10 L60,110 Z\" fill=\"#blue\"/><path d=\"M20,20 L120,20 L70,120 Z\" fill=\"#green\"/></g></svg>";
249
250	/// `OTSVG_DATA`. fontTools' test compresses with zlib; here with the same
251	/// implementation as the table (L25).
252	fn data() -> Vec<u8> {
253		let compressed = gzip(DOC1.as_bytes());
254		let mut out = Vec::new();
255		out.put_u16(0);
256		out.put_u32(10);
257		out.put_u32(0);
258		out.put_u16(3);
259		out.put_u16(1);
260		out.put_u16(2);
261		out.put_u32(0x26);
262		out.put_u32(DOC0.len() as u32);
263		out.put_u16(3);
264		out.put_u16(3);
265		out.put_u32(0x26 + DOC0.len() as u32);
266		out.put_u32(compressed.len() as u32);
267		out.put_u16(4);
268		out.put_u16(4);
269		out.put_u32(0x26);
270		out.put_u32(DOC0.len() as u32);
271		out.extend_from_slice(DOC0.as_bytes());
272		out.extend(compressed);
273		out
274	}
275
276	fn ttx() -> Vec<String> {
277		vec![
278			"<svgDoc endGlyphID=\"2\" startGlyphID=\"1\">".to_owned(),
279			format!("  <![CDATA[{DOC0}]]>"),
280			"</svgDoc>".to_owned(),
281			"<svgDoc compressed=\"1\" endGlyphID=\"3\" startGlyphID=\"3\">".to_owned(),
282			format!("  <![CDATA[{DOC1}]]>"),
283			"</svgDoc>".to_owned(),
284			"<svgDoc endGlyphID=\"4\" startGlyphID=\"4\">".to_owned(),
285			format!("  <![CDATA[{DOC0}]]>"),
286			"</svgDoc>".to_owned(),
287		]
288	}
289
290	fn get_xml(table: &Svg, font: &mut Font) -> Result<Vec<String>> {
291		let mut writer = XmlWriter::with_options("  ", "\n");
292		table.to_xml(&mut writer, font)?;
293		let text = writer.into_string();
294		let body = text.split_once('\n').map_or(text.as_str(), |(_, b)| b);
295		Ok(body.lines().map(str::to_owned).collect())
296	}
297
298	fn parse_ttx(lines: &[String], table: &mut Svg, font: &mut Font) -> Result<()> {
299		let doc = format!("<root>{}</root>", lines.join("\n"));
300		let root = xml_reader::parse(&doc).map_err(|e| Error::ttx(e.to_string()))?;
301		for element in root.elements() {
302			table.from_xml(element, font)?;
303		}
304		Ok(())
305	}
306
307	#[test]
308	fn decompile_and_compile() -> Result<()> {
309		let mut font = Font::new();
310		let mut table = Svg::decompile(&data(), &mut font)?;
311		assert_eq!(table.compile(&mut font)?, data());
312		Ok(())
313	}
314
315	#[test]
316	fn decompile_and_dump_ttx() -> Result<()> {
317		let mut font = Font::new();
318		let table = Svg::decompile(&data(), &mut font)?;
319		assert_eq!(get_xml(&table, &mut font)?, ttx());
320		Ok(())
321	}
322
323	#[test]
324	fn load_from_ttx_and_compile() -> Result<()> {
325		let mut font = Font::new();
326		let mut table = Svg::default();
327		parse_ttx(&ttx(), &mut table, &mut font)?;
328		assert_eq!(table.compile(&mut font)?, data());
329		Ok(())
330	}
331
332	#[test]
333	fn round_trip_ttx() -> Result<()> {
334		let mut font = Font::new();
335		let mut table = Svg::default();
336		parse_ttx(&ttx(), &mut table, &mut font)?;
337		let compiled = table.compile(&mut font)?;
338		let table = Svg::decompile(&compiled, &mut font)?;
339		assert_eq!(get_xml(&table, &mut font)?, ttx());
340		Ok(())
341	}
342
343	/// A document with `]]>` must not escape the CDATA section it is written into.
344	#[test]
345	fn round_trip_ttx_doc_containing_cdata_end() -> Result<()> {
346		let doc = "]]></svgDoc></SVG><name><namerecord nameID=\"6\" platformID=\"3\" platEncID=\"1\" langID=\"0x409\">x</namerecord></name><SVG><svgDoc startGlyphID=\"1\" endGlyphID=\"1\"><![CDATA[y";
347		let mut font = Font::new();
348		let table = Svg {
349			doc_list: Some(vec![SvgDocument {
350				data: doc.to_owned(),
351				start_glyph_id: 1,
352				end_glyph_id: 1,
353				compressed: false,
354			}]),
355			compressed: false,
356		};
357		let xml = get_xml(&table, &mut font)?;
358		let mut table = Svg::default();
359		parse_ttx(&xml, &mut table, &mut font)?;
360		let docs = table.doc_list.ok_or_else(no_doc_list)?;
361		assert_eq!(docs.len(), 1);
362		assert_eq!(docs[0].data, doc);
363		Ok(())
364	}
365
366	#[test]
367	fn compressed_documents() -> Result<()> {
368		let mut font = Font::new();
369		let table = Svg::decompile(&data(), &mut font)?;
370		let docs = table.doc_list.ok_or_else(no_doc_list)?;
371		assert_eq!(
372			docs.iter().map(|d| d.compressed).collect::<Vec<_>>(),
373			[false, true, false]
374		);
375		assert_eq!(docs[0].data, DOC0);
376		assert_eq!(docs[1].data, DOC1);
377		assert_eq!((docs[1].start_glyph_id, docs[1].end_glyph_id), (3, 3));
378		Ok(())
379	}
380}