Skip to main content

fontoxide_ttlib/tables/
hdmx.rs

1//! `hdmx` and `LTSH`: device metrics (`fontTools.ttLib.tables._h_d_m_x`,
2//! `L_T_S_H_`).
3
4use std::collections::BTreeMap;
5
6use fontoxide_misc::Tag;
7use fontoxide_misc::xml_reader::Element;
8use fontoxide_misc::xml_writer::XmlWriter;
9
10use crate::binary::{Reader, WriteBytes, fit};
11use crate::sstruct::{I32, U16, eval};
12use crate::table::{Table, TableType, TableXml};
13use crate::tables::Maxp;
14use crate::{Error, Font, Result};
15
16crate::sstruct! {
17	/// The `hdmx` header (`hdmxHeaderFormat`).
18	pub struct HdmxHeader = "hdmxHeaderFormat" {
19		/// 0.
20		pub version: u16 = "version" as U16,
21		/// Number of device records.
22		pub num_records: u16 = "numRecords" as U16,
23		/// Size of a device record, padded to a multiple of four.
24		pub record_size: i32 = "recordSize" as I32,
25	}
26}
27
28/// Horizontal Device Metrics table (`table__h_d_m_x`).
29///
30/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/hdmx>.
31#[derive(Debug, Clone, PartialEq, Default)]
32pub struct Hdmx {
33	/// Advance widths by ppem, then glyph ID (`hdmx`, keyed by glyph name in
34	/// fontTools).
35	pub hdmx: BTreeMap<u8, BTreeMap<u32, u8>>,
36}
37
38impl TableType for Hdmx {
39	const TAG: Tag = Tag::new(b"hdmx");
40
41	fn decompile(data: &[u8], font: &mut Font) -> Result<Self> {
42		// UPSTREAM-BUG(B27): `hdmx` only knows `maxp`, even in a font with `MAXP`.
43		let num_glyphs = font.require_locked::<Maxp>(false)?.num_glyphs as usize;
44		let glyph_count = font.glyph_order()?.len();
45		let (header, mut rest) = HdmxHeader::unpack2(data)?;
46		let mut hdmx = BTreeMap::new();
47		for _ in 0..header.num_records {
48			if rest.len() < 2 {
49				return Err(Error::ttlib("index out of range"));
50			}
51			let ppem = rest[0];
52			let widths = &rest[2..rest.len().min(2 + num_glyphs)];
53			// Widths are looked up by glyph ID; IDs past the data have none.
54			let map: BTreeMap<u32, u8> = (0..glyph_count.min(widths.len()))
55				.map(|gid| (gid as u32, widths[gid]))
56				.collect();
57			hdmx.insert(ppem, map);
58			rest = rest
59				.get(header.record_size.max(0) as usize..)
60				.unwrap_or_default();
61		}
62		if !rest.is_empty() {
63			return Err(Error::Assertion("too much hdmx data".into()));
64		}
65		Ok(Hdmx { hdmx })
66	}
67}
68
69impl Table for Hdmx {
70	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
71		for widths in self.hdmx.values_mut() {
72			*widths = crate::ot::aat::remap_keys(std::mem::take(widths), &mut *f)?;
73		}
74		Ok(())
75	}
76
77	fn tag(&self) -> Tag {
78		Self::TAG
79	}
80
81	fn compile(&mut self, font: &mut Font) -> Result<Vec<u8>> {
82		// UPSTREAM-BUG(B27): `hdmx` only knows `maxp`, even in a font with `MAXP`.
83		let num_glyphs = font.require_locked::<Maxp>(false)?.num_glyphs as usize;
84		let order = font.glyph_order()?;
85		let record_size = 4 * (2 + num_glyphs).div_ceil(4);
86		let pad = record_size - 2 - num_glyphs;
87		let mut data = Vec::new();
88		HdmxHeader {
89			version: 0,
90			num_records: fit(self.hdmx.len(), "numRecords")?,
91			record_size: fit(record_size, "recordSize")?,
92		}
93		.pack(&mut data)?;
94		for (&ppem, widths) in &self.hdmx {
95			let max = widths
96				.values()
97				.copied()
98				.max()
99				.ok_or_else(|| Error::value("max() arg is an empty sequence"))?;
100			data.put_u8(ppem);
101			data.put_u8(max);
102			for gid in 0..order.len() as u32 {
103				let width = widths
104					.get(&gid)
105					.ok_or_else(|| Error::GlyphNotFound(order.name(gid).into_owned()))?;
106				data.put_u8(*width);
107			}
108			data.resize(data.len() + pad, 0);
109		}
110		Ok(data)
111	}
112
113	fn clone_table(&self) -> Box<dyn Table> {
114		Box::new(self.clone())
115	}
116}
117
118impl TableXml for Hdmx {
119	fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font) -> Result<()> {
120		writer.begintag("hdmxData", &[]);
121		writer.newline();
122		let order = font.glyph_order()?;
123		let mut names: Vec<(&str, u32)> = order
124			.names()
125			.iter()
126			.enumerate()
127			.map(|(i, n)| (n.as_str(), i as u32))
128			.collect();
129		names.sort();
130		let width = names
131			.iter()
132			.map(|(n, _)| n.chars().count())
133			.max()
134			.unwrap_or(0);
135		let row = |label: &str, values: &[String]| format!("{label:>width$}:{} ;", values.concat());
136		let ppems: Vec<String> = self.hdmx.keys().map(|p| format!("{p:4}")).collect();
137		writer.write(&row("ppem", &ppems));
138		writer.newline();
139		writer.newline();
140		for (name, gid) in names {
141			let mut values = Vec::with_capacity(self.hdmx.len());
142			for widths in self.hdmx.values() {
143				let w = widths
144					.get(&gid)
145					.ok_or_else(|| Error::ttlib("array index out of range"))?;
146				values.push(format!("{w:4}"));
147			}
148			let label = name.replace(';', "\\x3b");
149			writer.write(&row(&label, &values));
150			writer.newline();
151		}
152		writer.endtag("hdmxData");
153		writer.newline();
154		Ok(())
155	}
156
157	fn from_xml(&mut self, element: &Element, font: &mut Font) -> Result<()> {
158		if element.name != "hdmxData" {
159			return Ok(());
160		}
161		let bad = || Error::Assertion("illegal hdmx format".into());
162		let int = |s: &str| -> Result<i128> {
163			fontoxide_misc::py::parse_int(s)
164				.ok_or_else(|| Error::value(format!("invalid literal for int(): {s:?}")))
165		};
166		let content = element.text();
167		let mut lines = content.split(';');
168		let top: Vec<&str> = lines
169			.next()
170			.unwrap_or_default()
171			.split_whitespace()
172			.collect();
173		if top.first() != Some(&"ppem:") {
174			return Err(bad());
175		}
176		let ppems: Vec<u8> = top[1..]
177			.iter()
178			.map(|s| int(s).and_then(|v| fit(v, "ppem")))
179			.collect::<Result<_>>()?;
180		self.hdmx = ppems.iter().map(|&p| (p, BTreeMap::new())).collect();
181		for line in lines {
182			let parts: Vec<&str> = line.split_whitespace().collect();
183			let Some(first) = parts.first() else {
184				continue;
185			};
186			let name = first.strip_suffix(':').ok_or_else(bad)?;
187			let name = if name.contains('\\') {
188				fontoxide_misc::text_tools::parse_string_body(name).ok_or_else(bad)?
189			} else {
190				name.to_owned()
191			};
192			if parts.len() - 1 != ppems.len() {
193				return Err(bad());
194			}
195			let gid = font.glyph_id(&name)?;
196			for (ppem, value) in ppems.iter().zip(&parts[1..]) {
197				let v: u8 = fit(int(value)?, "width")?;
198				if let Some(widths) = self.hdmx.get_mut(ppem) {
199					widths.insert(gid, v);
200				}
201			}
202		}
203		Ok(())
204	}
205}
206
207/// Linear Threshold table (`table_L_T_S_H_`).
208///
209/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/ltsh>.
210#[derive(Debug, Clone, PartialEq, Default)]
211pub struct Ltsh {
212	/// The ppem from which each glyph scales linearly, by glyph ID (`yPels`).
213	pub y_pels: BTreeMap<u32, u8>,
214}
215
216impl TableType for Ltsh {
217	const TAG: Tag = Tag::new(b"LTSH");
218
219	fn decompile(data: &[u8], _font: &mut Font) -> Result<Self> {
220		let mut r = Reader::new(data);
221		let version = r.u16()?;
222		let num_glyphs = r.u16()? as usize;
223		let rest = r.rest();
224		if version != 0 {
225			return Err(Error::Assertion(format!("unknown version: {version}")));
226		}
227		if num_glyphs == 0 {
228			return Err(Error::value("integer modulo by zero"));
229		}
230		if rest.len() % num_glyphs >= 4 {
231			return Err(Error::Assertion(
232				"numGlyphs doesn't match data length".into(),
233			));
234		}
235		if rest.len() < num_glyphs {
236			return Err(Error::ttlib("array index out of range"));
237		}
238		Ok(Ltsh {
239			y_pels: (0..num_glyphs).map(|i| (i as u32, rest[i])).collect(),
240		})
241	}
242}
243
244impl Table for Ltsh {
245	/// The values follow their glyphs (as when reordering glyphs); `f` fails for
246	/// glyphs that are dropped, which fontTools does not subset either.
247	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
248		let mut y_pels = BTreeMap::new();
249		for (gid, v) in std::mem::take(&mut self.y_pels) {
250			y_pels.insert(f(gid)?, v);
251		}
252		self.y_pels = y_pels;
253		Ok(())
254	}
255
256	fn tag(&self) -> Tag {
257		Self::TAG
258	}
259
260	fn compile(&mut self, _font: &mut Font) -> Result<Vec<u8>> {
261		let num_glyphs = self.y_pels.len();
262		let mut y_pels = vec![0u8; num_glyphs];
263		for (&gid, &v) in &self.y_pels {
264			*y_pels
265				.get_mut(gid as usize)
266				.ok_or_else(|| Error::ttlib("list assignment index out of range"))? = v;
267		}
268		let mut data = Vec::with_capacity(4 + num_glyphs);
269		data.put_u16(0);
270		data.put_u16(fit(num_glyphs, "numGlyphs")?);
271		data.extend(y_pels);
272		Ok(data)
273	}
274
275	fn clone_table(&self) -> Box<dyn Table> {
276		Box::new(self.clone())
277	}
278}
279
280impl TableXml for Ltsh {
281	fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font) -> Result<()> {
282		let order = font.glyph_order()?;
283		let mut entries: Vec<(String, u8)> = self
284			.y_pels
285			.iter()
286			.map(|(&gid, &v)| (order.name(gid).into_owned(), v))
287			.collect();
288		entries.sort();
289		for (name, value) in &entries {
290			writer.simpletag("yPel", &[("name", name), ("value", value)]);
291			writer.newline();
292		}
293		Ok(())
294	}
295
296	fn from_xml(&mut self, element: &Element, font: &mut Font) -> Result<()> {
297		if element.name != "yPel" {
298			return Ok(());
299		}
300		let name = element
301			.attr("name")
302			.ok_or_else(|| Error::ttx("missing 'name' on <yPel>"))?;
303		let value = element
304			.attr("value")
305			.ok_or_else(|| Error::ttx("missing 'value' on <yPel>"))?;
306		let v = eval(value)?
307			.as_int()
308			.ok_or_else(|| Error::value("invalid yPel value"))?;
309		let gid = font.glyph_id(name)?;
310		self.y_pels.insert(gid, fit(v, "yPel")?);
311		Ok(())
312	}
313}
314
315#[cfg(test)]
316mod tests {
317	use super::*;
318
319	#[test]
320	fn format_matches_upstream() {
321		crate::sstruct::tests::check(HdmxHeader::FORMAT_NAME, HdmxHeader::FIELDS);
322	}
323}