Skip to main content

fontoxide_ttlib/tables/
hhea.rs

1//! `hhea` and `vhea`: Horizontal and Vertical Header tables
2//! (`fontTools.ttLib.tables._h_h_e_a`, `_v_h_e_a`).
3
4use fontoxide_misc::Tag;
5use fontoxide_misc::fixed_tools::{ensure_version_is_long, version_to_fixed};
6use fontoxide_misc::xml_reader::Element;
7use fontoxide_misc::xml_writer::XmlWriter;
8
9use crate::binary::WriteBytes;
10use crate::sstruct::{I16, U16, U16Wide, U32, eval};
11use crate::table::{Table, TableType, TableXml};
12use crate::{Error, Font, Result};
13
14crate::sstruct! {
15	/// Horizontal Header table (`table__h_h_e_a`).
16	///
17	/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/hhea>.
18	pub struct Hhea = "hheaFormat" {
19		/// Table version, 0x00010000.
20		pub table_version: u32 = "tableVersion" as U32,
21		/// Typographic ascent (`ascender` in the OpenType specification).
22		pub ascent: i16 = "ascent" as I16,
23		/// Typographic descent (`descender` in the OpenType specification).
24		pub descent: i16 = "descent" as I16,
25		/// Typographic line gap.
26		pub line_gap: i16 = "lineGap" as I16,
27		/// Maximum advance width.
28		pub advance_width_max: u16 = "advanceWidthMax" as U16,
29		/// Minimum left side bearing of glyphs with contours.
30		pub min_left_side_bearing: i16 = "minLeftSideBearing" as I16,
31		/// Minimum right side bearing of glyphs with contours.
32		pub min_right_side_bearing: i16 = "minRightSideBearing" as I16,
33		/// Maximum of `lsb + (xMax - xMin)`.
34		pub x_max_extent: i16 = "xMaxExtent" as I16,
35		/// Slope of the caret: rise.
36		pub caret_slope_rise: i16 = "caretSlopeRise" as I16,
37		/// Slope of the caret: run.
38		pub caret_slope_run: i16 = "caretSlopeRun" as I16,
39		/// Caret offset for slanted fonts.
40		pub caret_offset: i16 = "caretOffset" as I16,
41		/// Reserved.
42		pub reserved0: i16 = "reserved0" as I16,
43		/// Reserved.
44		pub reserved1: i16 = "reserved1" as I16,
45		/// Reserved.
46		pub reserved2: i16 = "reserved2" as I16,
47		/// Reserved.
48		pub reserved3: i16 = "reserved3" as I16,
49		/// 0.
50		pub metric_data_format: i16 = "metricDataFormat" as I16,
51		/// Number of long metrics in `hmtx`.
52		pub number_of_h_metrics: u32 = "numberOfHMetrics" as U16Wide,
53	}
54	extra {
55		/// Whether this is `HHEA`, with a 32-bit `numberOfHMetrics`.
56		pub extended: bool,
57	}
58}
59
60crate::sstruct! {
61	/// Vertical Header table (`table__v_h_e_a`).
62	///
63	/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/vhea>.
64	pub struct Vhea = "vheaFormat" {
65		/// Table version, 0x00010000 or 0x00011000.
66		pub table_version: u32 = "tableVersion" as U32,
67		/// Vertical typographic ascender.
68		pub ascent: i16 = "ascent" as I16,
69		/// Vertical typographic descender.
70		pub descent: i16 = "descent" as I16,
71		/// Vertical typographic line gap.
72		pub line_gap: i16 = "lineGap" as I16,
73		/// Maximum advance height.
74		pub advance_height_max: u16 = "advanceHeightMax" as U16,
75		/// Minimum top side bearing of glyphs with contours.
76		pub min_top_side_bearing: i16 = "minTopSideBearing" as I16,
77		/// Minimum bottom side bearing of glyphs with contours.
78		pub min_bottom_side_bearing: i16 = "minBottomSideBearing" as I16,
79		/// Maximum of `tsb + (yMax - yMin)`.
80		pub y_max_extent: i16 = "yMaxExtent" as I16,
81		/// Slope of the caret: rise.
82		pub caret_slope_rise: i16 = "caretSlopeRise" as I16,
83		/// Slope of the caret: run.
84		pub caret_slope_run: i16 = "caretSlopeRun" as I16,
85		/// Caret offset (also called `reserved0` in fontTools).
86		pub caret_offset: i16 = "caretOffset" as I16,
87		/// Reserved.
88		pub reserved1: i16 = "reserved1" as I16,
89		/// Reserved.
90		pub reserved2: i16 = "reserved2" as I16,
91		/// Reserved.
92		pub reserved3: i16 = "reserved3" as I16,
93		/// Reserved.
94		pub reserved4: i16 = "reserved4" as I16,
95		/// 0.
96		pub metric_data_format: i16 = "metricDataFormat" as I16,
97		/// Number of long metrics in `vmtx`.
98		pub number_of_v_metrics: u32 = "numberOfVMetrics" as U16Wide,
99	}
100	extra {
101		/// Whether this is `VHEA`, with a 32-bit `numberOfVMetrics`.
102		pub extended: bool,
103	}
104}
105
106impl Hhea {
107	/// `ascender`, the OpenType specification's name for [`Hhea::ascent`].
108	pub fn ascender(&self) -> i16 {
109		self.ascent
110	}
111
112	/// `descender`, the OpenType specification's name for [`Hhea::descent`].
113	pub fn descender(&self) -> i16 {
114		self.descent
115	}
116}
117
118/// `fi2ve(tableVersion)`: a version below 0x10000 is taken as a float.
119fn version_as_long(v: u32) -> Result<u32> {
120	crate::binary::fit(ensure_version_is_long(v as f64), "tableVersion")
121}
122
123macro_rules! header_table {
124	($ty:ident, $tag:literal, $upper:literal, $count:ident) => {
125		impl TableType for $ty {
126			const TAG: Tag = Tag::new($tag);
127			const COMPANION: Option<Tag> = Some(Tag::new($upper));
128
129			fn decompile(data: &[u8], font: &mut Font) -> Result<Self> {
130				Self::decompile_as(Self::TAG, data, font)
131			}
132
133			fn decompile_as(tag: Tag, data: &[u8], _font: &mut Font) -> Result<Self> {
134				// sstruct.unpack requires the exact size.
135				let extended = tag == Tag::new($upper);
136				let size = if extended { Self::SIZE + 2 } else { Self::SIZE };
137				if data.len() != size {
138					return Err(Error::Struct(format!(
139						"unpack requires a buffer of {size} bytes"
140					)));
141				}
142				if !extended {
143					return Self::unpack2(data).map(|(t, _)| t);
144				}
145				// The count is the last field; the others are the same.
146				let (head, tail) = data.split_at(Self::SIZE - 2);
147				let mut packed = head.to_vec();
148				packed.extend_from_slice(&[0, 0]);
149				let (mut table, _) = Self::unpack2(&packed)?;
150				table.$count = u32::from_be_bytes([tail[0], tail[1], tail[2], tail[3]]);
151				table.extended = true;
152				Ok(table)
153			}
154
155			fn new_as(tag: Tag) -> Self {
156				Self {
157					extended: tag == Tag::new($upper),
158					..Default::default()
159				}
160			}
161		}
162
163		impl Table for $ty {
164			fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
165				let _ = f;
166				Ok(())
167			}
168
169			fn tag(&self) -> Tag {
170				Font::locked_tag::<Self>(self.extended)
171			}
172
173			fn compile(&mut self, font: &mut Font) -> Result<Vec<u8>> {
174				let glyf: &[u8; 4] = if self.extended { b"GLYF" } else { b"glyf" };
175				let outline_loaded = [glyf, b"CFF ", b"CFF2"]
176					.iter()
177					.any(|t| font.is_loaded(Tag::new(t)));
178				if font.recalc_bboxes && outline_loaded {
179					// `recalc` loads the metrics, whose decompiling needs this table,
180					// which is detached from the font while compiling: a copy with
181					// the values from before compiling stands in, as fontTools never
182					// detaches it.
183					font.insert(self.clone_table());
184					self.recalc(font)?;
185					font.insert(self.clone_table());
186				}
187				self.table_version = version_as_long(self.table_version)?;
188				let mut data = Vec::with_capacity(Self::SIZE + 2);
189				if self.extended {
190					// `L` instead of `H` for the last field.
191					let count = self.$count;
192					self.$count = 0;
193					let packed = self.pack(&mut data);
194					self.$count = count;
195					packed?;
196					data.truncate(Self::SIZE - 2);
197					data.put_u32(count);
198				} else {
199					self.pack(&mut data)?;
200				}
201				Ok(data)
202			}
203
204			fn clone_table(&self) -> Box<dyn Table> {
205				Box::new(self.clone())
206			}
207		}
208
209		impl TableXml for $ty {
210			fn to_xml(&self, writer: &mut XmlWriter, _font: &mut Font) -> Result<()> {
211				for (name, value) in self.values() {
212					if name == "tableVersion" {
213						let v = format!("0x{:08x}", version_as_long(self.table_version)?);
214						writer.simpletag(name, &[("value", &v)]);
215					} else {
216						writer.simpletag(name, &[("value", &value)]);
217					}
218					writer.newline();
219				}
220				Ok(())
221			}
222
223			fn from_xml(&mut self, element: &Element, _font: &mut Font) -> Result<()> {
224				let name = element.name.as_str();
225				let value = element
226					.attr("value")
227					.ok_or_else(|| Error::ttx(format!("missing 'value' on <{name}>")))?;
228				if name == "tableVersion" {
229					let v = version_to_fixed(value)
230						.ok_or_else(|| Error::value(format!("invalid version: {value:?}")))?;
231					self.table_version = crate::binary::fit(v, name)?;
232					return Ok(());
233				}
234				// The legacy alias `reserved0` of vhea's caretOffset.
235				let name = if self.tag().0.eq_ignore_ascii_case(b"vhea") && name == "reserved0" {
236					"caretOffset"
237				} else {
238					name
239				};
240				if !self.set_literal(name, &eval(value)?)? {
241					return Err(Error::ttx(format!(
242						"unknown '{}' field: {name}",
243						self.tag()
244					)));
245				}
246				Ok(())
247			}
248		}
249	};
250}
251
252header_table!(Hhea, b"hhea", b"HHEA", number_of_h_metrics);
253header_table!(Vhea, b"vhea", b"VHEA", number_of_v_metrics);
254
255impl Hhea {
256	/// Recalculates `advanceWidthMax`, the side bearing minima and `xMaxExtent`
257	/// from `hmtx` and the outlines (`recalc`).
258	pub fn recalc(&mut self, font: &mut Font) -> Result<()> {
259		let Some(r) = crate::tables::metrics::recalc_header(font, false, self.extended)? else {
260			return Ok(());
261		};
262		self.advance_width_max = r.advance_max;
263		self.min_left_side_bearing = r.min_start_side_bearing;
264		self.min_right_side_bearing = r.min_end_side_bearing;
265		self.x_max_extent = r.max_extent;
266		Ok(())
267	}
268}
269
270impl Vhea {
271	/// Recalculates `advanceHeightMax`, the side bearing minima and `yMaxExtent`
272	/// from `vmtx` and the outlines (`recalc`).
273	pub fn recalc(&mut self, font: &mut Font) -> Result<()> {
274		let Some(r) = crate::tables::metrics::recalc_header(font, true, self.extended)? else {
275			return Ok(());
276		};
277		self.advance_height_max = r.advance_max;
278		self.min_top_side_bearing = r.min_start_side_bearing;
279		self.min_bottom_side_bearing = r.min_end_side_bearing;
280		self.y_max_extent = r.max_extent;
281		Ok(())
282	}
283}
284
285#[cfg(test)]
286mod tests {
287	use super::*;
288
289	#[test]
290	fn formats_match_upstream() {
291		crate::sstruct::tests::check(Hhea::FORMAT_NAME, Hhea::FIELDS);
292		crate::sstruct::tests::check(Vhea::FORMAT_NAME, Vhea::FIELDS);
293	}
294}