Skip to main content

fontoxide_ttlib/tables/
sbix.rs

1//! `sbix`: Standard Bitmap Graphics table (`fontTools.ttLib.tables._s_b_i_x`,
2//! `sbixStrike`, `sbixGlyph`).
3
4use std::collections::BTreeMap;
5
6use fontoxide_misc::Tag;
7use fontoxide_misc::text_tools::{binary2num, num2binary, parse_string_body};
8use fontoxide_misc::xml_reader::Element;
9use fontoxide_misc::xml_writer::XmlWriter;
10
11use crate::binary::{Reader, fit};
12use crate::sstruct::{Bytes, I16, U16, U32, Value, eval};
13use crate::table::{Table, TableType, TableXml, read_hex};
14use crate::tables::eblc::{clip, int_attr, required_attr};
15use crate::{Error, Font, Result};
16
17crate::sstruct! {
18	/// The header (`sbixHeaderFormat`).
19	pub struct SbixHeader = "sbixHeaderFormat" {
20		/// The table version.
21		pub version: u16 = "version" as U16,
22		/// Flags.
23		pub flags: u16 = "flags" as U16,
24		/// The number of strikes.
25		pub num_strikes: u32 = "numStrikes" as U32,
26	}
27}
28
29crate::sstruct! {
30	/// The header of a strike (`sbixStrikeHeaderFormat`).
31	pub struct SbixStrikeHeader = "sbixStrikeHeaderFormat" {
32		/// The PPEM for which the strike was designed.
33		pub ppem: u16 = "ppem" as U16,
34		/// The screen resolution in dpi for which the strike was designed.
35		pub resolution: u16 = "resolution" as U16,
36	}
37}
38
39crate::sstruct! {
40	/// The header of a glyph data record (`sbixGlyphHeaderFormat`).
41	pub struct SbixGlyphHeader = "sbixGlyphHeaderFormat" {
42		/// The horizontal origin of the glyph.
43		pub origin_offset_x: i16 = "originOffsetX" as I16,
44		/// The vertical origin of the glyph.
45		pub origin_offset_y: i16 = "originOffsetY" as I16,
46		/// The type of the graphic, e.g. `png `.
47		pub graphic_type: [u8; 4] = "graphicType" as Bytes<4>,
48	}
49}
50
51/// A glyph data record (`Glyph`).
52#[derive(Debug, Clone, PartialEq, Eq, Default)]
53pub struct SbixGlyph {
54	/// The horizontal origin (`originOffsetX`).
55	pub origin_offset_x: i16,
56	/// The vertical origin (`originOffsetY`).
57	pub origin_offset_y: i16,
58	/// The type of the graphic; `None` for an empty record (`graphicType`).
59	pub graphic_type: Option<[u8; 4]>,
60	/// The image (`imageData`).
61	pub image_data: Option<Vec<u8>>,
62	/// The glyph whose image this one uses, for the `dupe` and `flip` types
63	/// (`referenceGlyphName`).
64	pub reference: Option<u32>,
65}
66
67impl SbixGlyph {
68	/// `is_reference_type`.
69	pub fn is_reference_type(&self) -> bool {
70		matches!(self.graphic_type.as_ref(), Some(b"dupe" | b"flip"))
71	}
72
73	fn decompile(raw: &[u8]) -> Result<Self> {
74		let mut glyph = SbixGlyph::default();
75		if raw.is_empty() {
76			return Ok(glyph);
77		}
78		if raw.len() < SbixGlyphHeader::SIZE {
79			return Err(Error::ttlib("Glyph header too short."));
80		}
81		let (header, rest) = SbixGlyphHeader::unpack2(raw)?;
82		glyph.origin_offset_x = header.origin_offset_x;
83		glyph.origin_offset_y = header.origin_offset_y;
84		glyph.graphic_type = Some(header.graphic_type);
85		if glyph.is_reference_type() {
86			if rest.len() != 2 {
87				return Err(Error::Struct(
88					"unpack requires a buffer of 2 bytes".to_owned(),
89				));
90			}
91			glyph.reference = Some(u32::from(Reader::new(rest).u16()?));
92		} else {
93			glyph.image_data = Some(rest.to_vec());
94		}
95		Ok(glyph)
96	}
97
98	/// `compile`, returning `rawdata`.
99	fn compile(&self, out: &mut Vec<u8>) -> Result<()> {
100		let Some(graphic_type) = self.graphic_type else {
101			return Ok(());
102		};
103		SbixGlyphHeader {
104			origin_offset_x: self.origin_offset_x,
105			origin_offset_y: self.origin_offset_y,
106			graphic_type,
107		}
108		.pack(out)?;
109		if self.is_reference_type() {
110			let reference = self
111				.reference
112				.ok_or_else(|| Error::ttlib("TypeError: no reference glyph"))?;
113			out.extend_from_slice(&fit::<u16, _>(reference, "referenceGlyph")?.to_be_bytes());
114		} else {
115			let image = self
116				.image_data
117				.as_ref()
118				.ok_or_else(|| Error::Assertion("self.imageData is not None".into()))?;
119			out.extend_from_slice(image);
120		}
121		Ok(())
122	}
123
124	fn to_xml(&self, writer: &mut XmlWriter, name: &str, font: &mut Font) -> Result<()> {
125		let Some(graphic_type) = &self.graphic_type else {
126			writer.simpletag("glyph", &[("name", &name)]);
127			writer.newline();
128			return Ok(());
129		};
130		writer.begintag(
131			"glyph",
132			&[
133				("graphicType", &Value::Bytes(graphic_type.to_vec())),
134				("name", &name),
135				("originOffsetX", &self.origin_offset_x),
136				("originOffsetY", &self.origin_offset_y),
137			],
138		);
139		writer.newline();
140		if self.is_reference_type() {
141			let reference = self
142				.reference
143				.ok_or_else(|| Error::ttlib("TypeError: no reference glyph"))?;
144			let reference = font.glyph_name(reference)?;
145			writer.simpletag("ref", &[("glyphname", &reference)]);
146		} else {
147			writer.begintag("hexdata", &[]);
148			writer.newline();
149			writer.dumphex(self.image_data.as_deref().unwrap_or_default());
150			writer.endtag("hexdata");
151		}
152		writer.newline();
153		writer.endtag("glyph");
154		writer.newline();
155		Ok(())
156	}
157
158	/// The `Glyph` constructor's clean-up of `graphicType`, for a `safeEval`ed
159	/// attribute.
160	fn graphic_type_from_str(value: &str) -> Result<[u8; 4]> {
161		let mut chars: Vec<char> = value.chars().collect();
162		match chars.last() {
163			None => return Err(Error::ttlib("IndexError: string index out of range")),
164			Some('\0') => {
165				chars.pop();
166			}
167			Some(_) => {}
168		}
169		if chars.len() > 4 {
170			return Err(Error::ttlib(
171				"Glyph.graphicType must not be longer than 4 characters.",
172			));
173		}
174		chars.resize(4, ' ');
175		let mut out = [0; 4];
176		for (o, c) in out.iter_mut().zip(chars) {
177			*o = u8::try_from(c)
178				.ok()
179				.filter(u8::is_ascii)
180				.ok_or_else(|| Error::value("'ascii' codec can't encode graphicType"))?;
181		}
182		Ok(out)
183	}
184
185	/// `Glyph.fromXML` followed by `compile`, for one child element.
186	fn child_from_xml(&mut self, element: &Element, font: &mut Font) -> Result<()> {
187		match element.name.as_str() {
188			"ref" => {
189				let name = string_literal(required_attr(element, "glyphname")?)?;
190				let gid = font.glyph_id(&name)?;
191				self.image_data = Some(fit::<u16, _>(gid, "glyphname")?.to_be_bytes().to_vec());
192				self.reference = Some(gid);
193			}
194			"hexdata" => self.image_data = Some(read_hex(element)?),
195			name => return Err(Error::ttlib(format!("can't handle '{name}' element"))),
196		}
197		self.compile(&mut Vec::new())
198	}
199}
200
201/// `safeEval("'''" + value + "'''")`.
202fn string_literal(value: &str) -> Result<String> {
203	parse_string_body(value).ok_or_else(|| Error::value(format!("malformed value: {value:?}")))
204}
205
206/// A strike: bitmaps for one size (`Strike`).
207#[derive(Debug, Clone, PartialEq, Eq)]
208pub struct SbixStrike {
209	/// The PPEM for which the strike was designed (`ppem`).
210	pub ppem: u16,
211	/// The screen resolution in dpi for which the strike was designed
212	/// (`resolution`).
213	pub resolution: u16,
214	/// The glyph data records by glyph ID (`glyphs`, by glyph name in fontTools).
215	pub glyphs: BTreeMap<u32, SbixGlyph>,
216}
217
218impl Default for SbixStrike {
219	fn default() -> Self {
220		SbixStrike {
221			ppem: 0,
222			resolution: 72,
223			glyphs: BTreeMap::new(),
224		}
225	}
226}
227
228impl SbixStrike {
229	fn decompile(raw: &[u8]) -> Result<Self> {
230		if raw.len() < SbixStrikeHeader::SIZE {
231			return Err(Error::ttlib("Strike header too short."));
232		}
233		let (header, rest) = SbixStrikeHeader::unpack2(raw)?;
234		let first = Reader::new(rest).u32()?;
235		// One more offset than glyphs.
236		let num_glyphs = (i64::from(first) - 4).div_euclid(4) - 1;
237		let count = (num_glyphs + 1).max(0) as usize;
238		let offsets = Reader::new(rest).u32_array(count)?;
239		let mut glyphs = BTreeMap::new();
240		for (gid, pair) in offsets.windows(2).enumerate() {
241			let data = clip(raw, u64::from(pair[0]), u64::from(pair[1]));
242			glyphs.insert(gid as u32, SbixGlyph::decompile(data)?);
243		}
244		Ok(SbixStrike {
245			ppem: header.ppem,
246			resolution: header.resolution,
247			glyphs,
248		})
249	}
250
251	fn compile(&self, num_glyphs: usize) -> Result<Vec<u8>> {
252		let mut bitmap_data = Vec::new();
253		let mut out = Vec::new();
254		SbixStrikeHeader {
255			ppem: self.ppem,
256			resolution: self.resolution,
257		}
258		.pack(&mut out)?;
259		let base = SbixStrikeHeader::SIZE + 4 * (num_glyphs + 1);
260		for gid in 0..num_glyphs {
261			let offset: u32 = fit(base + bitmap_data.len(), "glyphDataOffset")?;
262			out.extend_from_slice(&offset.to_be_bytes());
263			if let Some(glyph) = self.glyphs.get(&(gid as u32)) {
264				glyph.compile(&mut bitmap_data)?;
265			}
266		}
267		let offset: u32 = fit(base + bitmap_data.len(), "glyphDataOffset")?;
268		out.extend_from_slice(&offset.to_be_bytes());
269		out.extend(bitmap_data);
270		Ok(out)
271	}
272
273	fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font) -> Result<()> {
274		writer.begintag("strike", &[]);
275		writer.newline();
276		writer.simpletag("ppem", &[("value", &self.ppem)]);
277		writer.newline();
278		writer.simpletag("resolution", &[("value", &self.resolution)]);
279		writer.newline();
280		let order = font.glyph_order()?;
281		for (gid, name) in order.names().iter().enumerate() {
282			if let Some(glyph) = self.glyphs.get(&(gid as u32)) {
283				glyph.to_xml(writer, name, font)?;
284			}
285		}
286		writer.endtag("strike");
287		writer.newline();
288		Ok(())
289	}
290
291	fn child_from_xml(&mut self, element: &Element, font: &mut Font) -> Result<()> {
292		match element.name.as_str() {
293			"ppem" => self.ppem = int_attr(element, "value")?,
294			"resolution" => self.resolution = int_attr(element, "value")?,
295			"glyph" => {
296				let mut glyph = SbixGlyph::default();
297				if let Some(value) = element.attr("graphicType") {
298					glyph.graphic_type =
299						Some(SbixGlyph::graphic_type_from_str(&string_literal(value)?)?);
300				}
301				let name = element
302					.attr("glyphname")
303					.or_else(|| element.attr("name"))
304					.ok_or_else(|| Error::ttlib("Glyph must have a glyph name."))?;
305				let gid = font.glyph_id(&string_literal(name)?)?;
306				if element.attr("originOffsetX").is_some() {
307					glyph.origin_offset_x = int_attr(element, "originOffsetX")?;
308				}
309				if element.attr("originOffsetY").is_some() {
310					glyph.origin_offset_y = int_attr(element, "originOffsetY")?;
311				}
312				for child in element.elements() {
313					glyph.child_from_xml(child, font)?;
314				}
315				self.glyphs.insert(gid, glyph);
316			}
317			name => return Err(Error::ttlib(format!("can't handle '{name}' element"))),
318		}
319		Ok(())
320	}
321}
322
323/// Standard Bitmap Graphics table (`table__s_b_i_x`).
324///
325/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/sbix>.
326#[derive(Debug, Clone, PartialEq, Eq)]
327pub struct Sbix {
328	/// The table version.
329	pub version: u16,
330	/// Flags.
331	pub flags: u16,
332	/// The strikes, by ppem (`strikes`).
333	pub strikes: BTreeMap<u16, SbixStrike>,
334}
335
336impl Default for Sbix {
337	fn default() -> Self {
338		Sbix {
339			version: 1,
340			flags: 1,
341			strikes: BTreeMap::new(),
342		}
343	}
344}
345
346impl TableType for Sbix {
347	const TAG: Tag = Tag::new(b"sbix");
348
349	fn decompile(data: &[u8], _font: &mut Font) -> Result<Self> {
350		let (header, rest) = SbixHeader::unpack2(data)?;
351		let offsets = Reader::new(rest).u32_array(header.num_strikes as usize)?;
352		let mut strikes = BTreeMap::new();
353		// Each strike ends where the next one starts.
354		let mut end = data.len() as u64;
355		for &offset in offsets.iter().rev() {
356			let offset = u64::from(offset);
357			let strike = SbixStrike::decompile(clip(data, offset, end))?;
358			end = end.min(offset);
359			if strikes.insert(strike.ppem, strike).is_some() {
360				return Err(Error::ttlib("Pixel 'ppem' must be unique for each Strike"));
361			}
362		}
363		Ok(Sbix {
364			version: header.version,
365			flags: header.flags,
366			strikes,
367		})
368	}
369}
370
371impl Table for Sbix {
372	fn tag(&self) -> Tag {
373		Self::TAG
374	}
375
376	fn compile(&mut self, font: &mut Font) -> Result<Vec<u8>> {
377		let num_glyphs = font.glyph_order()?.len();
378		let mut header = Vec::new();
379		SbixHeader {
380			version: self.version,
381			flags: self.flags,
382			num_strikes: fit(self.strikes.len(), "numStrikes")?,
383		}
384		.pack(&mut header)?;
385		let mut offset = SbixHeader::SIZE + 4 * self.strikes.len();
386		let mut strike_data = Vec::new();
387		for strike in self.strikes.values() {
388			let data = strike.compile(num_glyphs)?;
389			let strike_offset: u32 = fit(offset, "strikeOffset")?;
390			header.extend_from_slice(&strike_offset.to_be_bytes());
391			offset += data.len();
392			strike_data.extend(data);
393		}
394		header.extend(strike_data);
395		Ok(header)
396	}
397
398	fn clone_table(&self) -> Box<dyn Table> {
399		Box::new(self.clone())
400	}
401
402	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
403		for strike in self.strikes.values_mut() {
404			let glyphs = std::mem::take(&mut strike.glyphs);
405			for (gid, mut glyph) in glyphs {
406				if let Some(reference) = &mut glyph.reference {
407					*reference = f(*reference)?;
408				}
409				strike.glyphs.insert(f(gid)?, glyph);
410			}
411		}
412		Ok(())
413	}
414}
415
416impl TableXml for Sbix {
417	fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font) -> Result<()> {
418		writer.simpletag("version", &[("value", &self.version)]);
419		writer.newline();
420		writer.simpletag(
421			"flags",
422			&[("value", &num2binary(i64::from(self.flags), 16))],
423		);
424		writer.newline();
425		for strike in self.strikes.values() {
426			strike.to_xml(writer, font)?;
427		}
428		Ok(())
429	}
430
431	fn from_xml(&mut self, element: &Element, font: &mut Font) -> Result<()> {
432		match element.name.as_str() {
433			"version" => {
434				self.version = fit(
435					eval(required_attr(element, "value")?)?
436						.as_int()
437						.ok_or_else(|| Error::value("invalid value for version"))?,
438					"version",
439				)?;
440			}
441			"flags" => {
442				self.flags = fit(binary2num(required_attr(element, "value")?), "flags")?;
443			}
444			"strike" => {
445				let mut strike = SbixStrike::default();
446				for child in element.elements() {
447					strike.child_from_xml(child, font)?;
448				}
449				self.strikes.insert(strike.ppem, strike);
450			}
451			name => return Err(Error::ttlib(format!("can't handle '{name}' element"))),
452		}
453		Ok(())
454	}
455}
456
457#[cfg(test)]
458mod tests {
459	use super::*;
460
461	#[test]
462	fn formats_match_upstream() {
463		use crate::sstruct::tests::check;
464		check(SbixHeader::FORMAT_NAME, SbixHeader::FIELDS);
465		check(SbixStrikeHeader::FORMAT_NAME, SbixStrikeHeader::FIELDS);
466		check(SbixGlyphHeader::FORMAT_NAME, SbixGlyphHeader::FIELDS);
467	}
468
469	#[test]
470	fn graphic_type_clean_up() -> Result<()> {
471		assert_eq!(SbixGlyph::graphic_type_from_str("png")?, *b"png ");
472		assert_eq!(SbixGlyph::graphic_type_from_str("png\0")?, *b"png ");
473		assert!(SbixGlyph::graphic_type_from_str("pngxy").is_err());
474		assert!(SbixGlyph::graphic_type_from_str("").is_err());
475		Ok(())
476	}
477}