Skip to main content

fontoxide_ttlib/tables/
ebsc.rs

1//! `EBSC`: the Embedded Bitmap Scaling table (`fontTools.ttLib.tables.E_B_S_C_`).
2//!
3//! See <https://learn.microsoft.com/en-us/typography/opentype/spec/ebsc>.
4
5use fontoxide_misc::Tag;
6use fontoxide_misc::xml_reader::Element;
7use fontoxide_misc::xml_writer::XmlWriter;
8
9use crate::binary::fit;
10use crate::sstruct::{F16Dot16, U8, U32, Value, eval};
11use crate::table::{Table, TableType, TableXml};
12use crate::tables::eblc::SbitLineMetrics;
13use crate::{Error, Font, Result};
14
15crate::sstruct! {
16	/// The header (`ebscHeaderFormat`).
17	pub struct EbscHeader = "ebscHeaderFormat" {
18		/// The table version.
19		pub version: f64 = "version" as F16Dot16,
20		/// The number of bitmap scale tables.
21		pub num_sizes: u32 = "numSizes" as U32,
22	}
23}
24
25crate::sstruct! {
26	/// The sizes of a bitmap scale table (`bitmapScaleTableFormatPart2`).
27	pub struct BitmapScalePart2 = "bitmapScaleTableFormatPart2" {
28		/// Target horizontal pixels per em.
29		pub ppem_x: u8 = "ppemX" as U8,
30		/// Target vertical pixels per em.
31		pub ppem_y: u8 = "ppemY" as U8,
32		/// Horizontal pixels per em of the strike to scale.
33		pub substitute_ppem_x: u8 = "substitutePpemX" as U8,
34		/// Vertical pixels per em of the strike to scale.
35		pub substitute_ppem_y: u8 = "substitutePpemY" as U8,
36	}
37}
38
39/// A strike made by scaling another one (`BitmapScaleTable`).
40///
41/// LENIENT(L22): line metrics that a TTX document leaves out are zero.
42#[derive(Debug, Clone, PartialEq, Default)]
43pub struct BitmapScaleTable {
44	/// Horizontal line metrics (`hori`).
45	pub hori: SbitLineMetrics,
46	/// Vertical line metrics (`vert`).
47	pub vert: SbitLineMetrics,
48	/// The sizes.
49	pub part2: BitmapScalePart2,
50}
51
52impl BitmapScaleTable {
53	const SIZE: usize = 2 * SbitLineMetrics::SIZE + BitmapScalePart2::SIZE;
54
55	fn to_xml(&self, index: usize, writer: &mut XmlWriter) {
56		writer.begintag_ordered("bitmapScaleTable", &[("index", &index)]);
57		writer.newline();
58		for (name, metrics) in [("hori", &self.hori), ("vert", &self.vert)] {
59			writer.begintag_ordered("sbitLineMetrics", &[("direction", &name)]);
60			writer.newline();
61			for (field, value) in metrics.values() {
62				writer.simpletag(field, &[("value", &value)]);
63				writer.newline();
64			}
65			writer.endtag("sbitLineMetrics");
66			writer.newline();
67		}
68		for (field, value) in self.part2.values() {
69			writer.simpletag(field, &[("value", &value)]);
70			writer.newline();
71		}
72		writer.endtag("bitmapScaleTable");
73		writer.newline();
74	}
75
76	fn read_xml(element: &Element) -> Result<Self> {
77		let mut table = BitmapScaleTable::default();
78		for child in element.elements() {
79			if child.name == "sbitLineMetrics" {
80				let direction = child
81					.attr("direction")
82					.ok_or_else(|| Error::ttx("missing 'direction' on <sbitLineMetrics>"))?;
83				if direction != "hori" && direction != "vert" {
84					return Err(Error::ttlib(format!(
85						"invalid sbitLineMetrics direction: {}",
86						fontoxide_misc::py::str_repr(direction)
87					)));
88				}
89				let mut metrics = SbitLineMetrics::default();
90				for m in child.elements() {
91					if SbitLineMetrics::FIELDS.iter().any(|f| f.name == m.name) {
92						metrics.set_literal(&m.name, &value_literal(m)?)?;
93					}
94				}
95				if direction == "hori" {
96					table.hori = metrics;
97				} else {
98					table.vert = metrics;
99				}
100			} else if BitmapScalePart2::FIELDS
101				.iter()
102				.any(|f| f.name == child.name)
103			{
104				table
105					.part2
106					.set_literal(&child.name, &value_literal(child)?)?;
107			}
108		}
109		Ok(table)
110	}
111}
112
113fn value_literal(element: &Element) -> Result<fontoxide_misc::text_tools::Literal> {
114	eval(
115		element
116			.attr("value")
117			.ok_or_else(|| Error::ttx(format!("missing 'value' on <{}>", element.name)))?,
118	)
119}
120
121/// Embedded Bitmap Scaling table (`table_E_B_S_C_`).
122#[derive(Debug, Clone, PartialEq)]
123pub struct Ebsc {
124	/// The table version: a float when decompiled, as written in TTX otherwise.
125	pub version: Value,
126	/// The number of sizes as read; recalculated when compiling.
127	pub num_sizes: i64,
128	/// The bitmap scale tables (`bitmapScaleTables`).
129	pub bitmap_scale_tables: Vec<BitmapScaleTable>,
130}
131
132impl Default for Ebsc {
133	fn default() -> Self {
134		Ebsc {
135			version: Value::Float(2.0),
136			num_sizes: 0,
137			bitmap_scale_tables: Vec::new(),
138		}
139	}
140}
141
142impl TableType for Ebsc {
143	const TAG: Tag = Tag::new(b"EBSC");
144
145	fn decompile(data: &[u8], _font: &mut Font) -> Result<Self> {
146		let (header, mut rest) = EbscHeader::unpack2(data)?;
147		let mut tables = Vec::new();
148		for _ in 0..header.num_sizes {
149			if rest.len() < BitmapScaleTable::SIZE {
150				// The first of the three structures that is too short fails.
151				let size = if rest.len() < 2 * SbitLineMetrics::SIZE {
152					SbitLineMetrics::SIZE
153				} else {
154					BitmapScalePart2::SIZE
155				};
156				return Err(Error::Struct(format!(
157					"unpack requires a buffer of {size} bytes"
158				)));
159			}
160			let (hori, r) = SbitLineMetrics::unpack2(rest)?;
161			let (vert, r) = SbitLineMetrics::unpack2(r)?;
162			let (part2, r) = BitmapScalePart2::unpack2(r)?;
163			rest = r;
164			tables.push(BitmapScaleTable { hori, vert, part2 });
165		}
166		Ok(Ebsc {
167			version: Value::Float(header.version),
168			num_sizes: i64::from(header.num_sizes),
169			bitmap_scale_tables: tables,
170		})
171	}
172}
173
174impl Table for Ebsc {
175	fn tag(&self) -> Tag {
176		Self::TAG
177	}
178
179	fn compile(&mut self, _font: &mut Font) -> Result<Vec<u8>> {
180		self.num_sizes = self.bitmap_scale_tables.len() as i64;
181		let version = match &self.version {
182			Value::Int(i) => *i as f64,
183			Value::Float(f) => *f,
184			Value::Bytes(_) => return Err(Error::value("invalid version")),
185		};
186		let mut out = Vec::new();
187		EbscHeader {
188			version,
189			num_sizes: fit(self.num_sizes, "numSizes")?,
190		}
191		.pack(&mut out)?;
192		for table in &self.bitmap_scale_tables {
193			table.hori.pack(&mut out)?;
194			table.vert.pack(&mut out)?;
195			table.part2.pack(&mut out)?;
196		}
197		Ok(out)
198	}
199
200	fn clone_table(&self) -> Box<dyn Table> {
201		Box::new(self.clone())
202	}
203
204	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
205		let _ = f;
206		Ok(())
207	}
208}
209
210impl TableXml for Ebsc {
211	fn to_xml(&self, writer: &mut XmlWriter, _font: &mut Font) -> Result<()> {
212		writer.simpletag_ordered(
213			"header",
214			&[
215				("version", &self.version),
216				("numSizes", &self.bitmap_scale_tables.len()),
217			],
218		);
219		writer.newline();
220		for (index, table) in self.bitmap_scale_tables.iter().enumerate() {
221			table.to_xml(index, writer);
222		}
223		Ok(())
224	}
225
226	fn from_xml(&mut self, element: &Element, _font: &mut Font) -> Result<()> {
227		match element.name.as_str() {
228			"header" => {
229				let attr = |name: &str| {
230					element
231						.attr(name)
232						.ok_or_else(|| Error::ttx(format!("missing '{name}' on <header>")))
233				};
234				let version = eval(attr("version")?)?;
235				self.version = match version.as_int() {
236					Some(i) => Value::Int(fit(i, "version")?),
237					None => Value::Float(
238						version
239							.as_float()
240							.ok_or_else(|| Error::value("invalid value for version"))?,
241					),
242				};
243				self.num_sizes = fit(
244					eval(attr("numSizes")?)?
245						.as_int()
246						.ok_or_else(|| Error::value("invalid value for numSizes"))?,
247					"numSizes",
248				)?;
249			}
250			"bitmapScaleTable" => {
251				self.bitmap_scale_tables
252					.push(BitmapScaleTable::read_xml(element)?);
253			}
254			_ => {}
255		}
256		Ok(())
257	}
258}
259
260#[cfg(test)]
261mod tests {
262	use super::*;
263
264	#[test]
265	fn formats_match_upstream() {
266		use crate::sstruct::tests::check;
267		check(EbscHeader::FORMAT_NAME, EbscHeader::FIELDS);
268		check(BitmapScalePart2::FORMAT_NAME, BitmapScalePart2::FIELDS);
269	}
270}