Skip to main content

fontoxide_ttlib/tables/
head.rs

1//! `head`: Font Header table (`fontTools.ttLib.tables._h_e_a_d`), and `bhed`
2//! (`_b_h_e_d`).
3
4use fontoxide_misc::Tag;
5use fontoxide_misc::fixed_tools::{float_to_fixed_to_str, str_to_fixed_to_float};
6use fontoxide_misc::text_tools::{binary2num, num2binary};
7use fontoxide_misc::time_tools::{
8	EPOCH_DIFF, timestamp_from_string, timestamp_now, timestamp_to_string,
9};
10use fontoxide_misc::xml_reader::Element;
11use fontoxide_misc::xml_writer::XmlWriter;
12
13use crate::sstruct::{F16Dot16, I16, U16, U32, U64, Value, eval};
14use crate::table::{Table, TableType, TableXml};
15use crate::{Error, Font, Result};
16
17/// The error when `recalc_timestamp` is on but there is no current time.
18pub(crate) const NO_TIMESTAMP: &str =
19	"invalid SOURCE_DATE_EPOCH or no clock (on wasm, call fontoxide_ttlib::set_clock first)";
20
21crate::sstruct! {
22	/// Font Header table (`table__h_e_a_d`).
23	///
24	/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/head>.
25	pub struct Head = "headFormat" {
26		/// Table version, normally 1.0.
27		pub table_version: f64 = "tableVersion" as F16Dot16,
28		/// Font revision, set by the font manufacturer.
29		pub font_revision: f64 = "fontRevision" as F16Dot16,
30		/// Set when the font is compiled so that the font checksum is 0xB1B0AFBA.
31		pub check_sum_adjustment: u32 = "checkSumAdjustment" as U32,
32		/// 0x5F0F3CF5.
33		pub magic_number: u32 = "magicNumber" as U32,
34		/// Flags.
35		pub flags: u16 = "flags" as U16,
36		/// Units per em.
37		pub units_per_em: u16 = "unitsPerEm" as U16,
38		/// Creation time, in seconds since 1904-01-01.
39		pub created: u64 = "created" as U64,
40		/// Modification time, in seconds since 1904-01-01.
41		pub modified: u64 = "modified" as U64,
42		/// Bounding box of all glyphs.
43		pub x_min: i16 = "xMin" as I16,
44		/// Bounding box of all glyphs.
45		pub y_min: i16 = "yMin" as I16,
46		/// Bounding box of all glyphs.
47		pub x_max: i16 = "xMax" as I16,
48		/// Bounding box of all glyphs.
49		pub y_max: i16 = "yMax" as I16,
50		/// Bold, italic, … flags.
51		pub mac_style: u16 = "macStyle" as U16,
52		/// Smallest readable size in pixels.
53		pub lowest_rec_ppem: u16 = "lowestRecPPEM" as U16,
54		/// Deprecated; set to 2.
55		pub font_direction_hint: i16 = "fontDirectionHint" as I16,
56		/// 0 for short `loca` offsets, 1 for long.
57		pub index_to_loc_format: i16 = "indexToLocFormat" as I16,
58		/// 0.
59		pub glyph_data_format: i16 = "glyphDataFormat" as I16,
60	}
61}
62
63impl TableType for Head {
64	const TAG: Tag = Tag::new(b"head");
65
66	fn decompile(data: &[u8], _font: &mut Font) -> Result<Self> {
67		let (mut head, rest) = Head::unpack2(data)?;
68		if !rest.is_empty() {
69			// Quite illegal, but there seem to be fonts out there that do this.
70			log::warn!("extra bytes at the end of 'head' table");
71			if rest != b"\0\0" {
72				return Err(Error::Assertion("rest == b'\\0\\0'".into()));
73			}
74		}
75		// For timestamp fields, ignore the top four bytes. Some fonts have bogus
76		// values there. Since till 2038 those bytes only can be zero, ignore them.
77		for (name, stamp) in [
78			("created", &mut head.created),
79			("modified", &mut head.modified),
80		] {
81			if *stamp > 0xFFFF_FFFF {
82				log::warn!("'{name}' timestamp out of range; ignoring top bytes");
83				*stamp &= 0xFFFF_FFFF;
84			}
85			// `-mac_epoch_diff`: January 1, 1970 00:00:00.
86			let unix_epoch = EPOCH_DIFF.unsigned_abs();
87			if *stamp < unix_epoch {
88				log::warn!("'{name}' timestamp seems very low; regarding as unix timestamp");
89				*stamp += unix_epoch;
90			}
91		}
92		Ok(head)
93	}
94}
95
96impl Head {
97	fn set_bbox(&mut self, [x_min, y_min, x_max, y_max]: [i64; 4]) -> Result<()> {
98		self.x_min = crate::binary::fit(x_min, "xMin")?;
99		self.y_min = crate::binary::fit(y_min, "yMin")?;
100		self.x_max = crate::binary::fit(x_max, "xMax")?;
101		self.y_max = crate::binary::fit(y_max, "yMax")?;
102		Ok(())
103	}
104
105	/// `compile`; while the outlines are loaded, `stand_in` makes a copy of the
106	/// table to stand in for it in the font.
107	fn compile_with(
108		&mut self,
109		font: &mut Font,
110		stand_in: fn(&Head) -> Box<dyn Table>,
111	) -> Result<Vec<u8>> {
112		if font.recalc_bboxes {
113			// For TrueType-flavored fonts, the bounding box is set in maxp.recalc().
114			if font.contains(Tag::new(b"VARC")) {
115				// Loading the outlines may need this table, which is detached from the
116				// font while compiling; a copy stands in until that is over.
117				font.insert(stand_in(self));
118				let glyph_set = crate::glyph_set::GlyphSet::new(font)?;
119				let mut pen = fontoxide_pens::BoundsPen::new_bounds(Some(&glyph_set));
120				for name in glyph_set.glyph_order().names() {
121					glyph_set.draw(name, &mut pen)?;
122				}
123				if let Some(b) = pen.bounds() {
124					self.set_bbox(fontoxide_misc::array_tools::int_rect(b))?;
125				}
126			} else if font.contains(Tag::new(b"CFF ")) {
127				let cff = &font.require::<crate::tables::Cff>()?.cff;
128				let top = cff
129					.top_dicts
130					.first()
131					.ok_or_else(crate::cff::charstring::index_error)?;
132				let bbox = top
133					.get("FontBBox")
134					.ok_or_else(|| Error::ttlib("AttributeError: FontBBox"))?;
135				let rect = match &bbox {
136					crate::cff::dict::Value::List(v) if v.len() == 4 => {
137						let n = |i: usize| {
138							v[i].number()
139								.ok_or_else(|| Error::ttlib("TypeError: must be real number"))
140						};
141						[n(0)?, n(1)?, n(2)?, n(3)?]
142					}
143					_ => return Err(Error::value("not enough values to unpack (expected 4)")),
144				};
145				self.set_bbox(fontoxide_misc::array_tools::int_rect(rect))?;
146			} else if font.contains(Tag::new(b"CFF2"))
147				&& let Some(rect) = font.require::<crate::tables::Cff2>()?.cff.font_bounds()?
148			{
149				self.set_bbox(fontoxide_misc::array_tools::int_rect(rect))?;
150			}
151		}
152		if font.recalc_timestamp {
153			let now = timestamp_now().ok_or_else(|| Error::value(NO_TIMESTAMP))?;
154			self.modified = crate::binary::fit(now, "modified")?;
155		}
156		let mut data = Vec::with_capacity(Self::SIZE);
157		self.pack(&mut data)?;
158		Ok(data)
159	}
160}
161
162impl Table for Head {
163	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
164		let _ = f;
165		Ok(())
166	}
167
168	fn tag(&self) -> Tag {
169		Self::TAG
170	}
171
172	fn compile(&mut self, font: &mut Font) -> Result<Vec<u8>> {
173		self.compile_with(font, |head| Box::new(head.clone()))
174	}
175
176	fn clone_table(&self) -> Box<dyn Table> {
177		Box::new(self.clone())
178	}
179}
180
181impl TableXml for Head {
182	fn to_xml(&self, writer: &mut XmlWriter, _font: &mut Font) -> Result<()> {
183		writer.comment("Most of this table will be recalculated by the compiler");
184		writer.newline();
185		for (field, (name, value)) in Self::FIELDS.iter().zip(self.values()) {
186			let text = match (name, value) {
187				(_, Value::Float(f)) => float_to_fixed_to_str(f, field.fraction_bits.unwrap_or(16)),
188				("created" | "modified", Value::Int(i)) => timestamp_to_string(i),
189				("magicNumber" | "checkSumAdjustment", Value::Int(i)) => format!("{i:#x}"),
190				("macStyle" | "flags", Value::Int(i)) => num2binary(i, 16),
191				(_, v) => fontoxide_misc::xml_writer::AttrValue::attr_string(&v).into_owned(),
192			};
193			writer.simpletag(name, &[("value", &text)]);
194			writer.newline();
195		}
196		Ok(())
197	}
198
199	fn from_xml(&mut self, element: &Element, _font: &mut Font) -> Result<()> {
200		let name = element.name.as_str();
201		let value = element
202			.attr("value")
203			.ok_or_else(|| Error::ttx(format!("missing 'value' on <{name}>")))?;
204		let fixed = Self::FIELDS
205			.iter()
206			.find(|f| f.name == name)
207			.and_then(|f| f.fraction_bits);
208		match name {
209			_ if fixed.is_some() => {
210				let v = str_to_fixed_to_float(value, fixed.unwrap_or(16)).ok_or_else(|| {
211					Error::value(format!("could not convert string to float: {value:?}"))
212				})?;
213				let lit = fontoxide_misc::text_tools::Literal::Float(v);
214				self.set_literal(name, &lit)?;
215			}
216			"created" | "modified" => {
217				let t = timestamp_from_string(value)
218					.ok_or_else(|| Error::value(format!("invalid timestamp: {value:?}")))?;
219				let t: u64 = crate::binary::fit(t, name)?;
220				if name == "created" {
221					self.created = t;
222				} else {
223					self.modified = t;
224				}
225			}
226			"macStyle" | "flags" => {
227				let v: u16 = crate::binary::fit(binary2num(value), name)?;
228				if name == "flags" {
229					self.flags = v;
230				} else {
231					self.mac_style = v;
232				}
233			}
234			_ => {
235				if !self.set_literal(name, &eval(value)?)? {
236					return Err(Error::ttx(format!("unknown 'head' field: {name}")));
237				}
238			}
239		}
240		Ok(())
241	}
242}
243
244/// Apple's bitmap-only font header (`table__b_h_e_d`): a `head` table under the
245/// tag `bhed`, with the same binary and TTX forms.
246#[derive(Debug, Clone, PartialEq, Default)]
247pub struct Bhed(pub Head);
248
249impl std::ops::Deref for Bhed {
250	type Target = Head;
251
252	fn deref(&self) -> &Head {
253		&self.0
254	}
255}
256
257impl std::ops::DerefMut for Bhed {
258	fn deref_mut(&mut self) -> &mut Head {
259		&mut self.0
260	}
261}
262
263impl TableType for Bhed {
264	const TAG: Tag = Tag::new(b"bhed");
265
266	fn decompile(data: &[u8], font: &mut Font) -> Result<Self> {
267		Head::decompile(data, font).map(Bhed)
268	}
269}
270
271impl Table for Bhed {
272	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
273		self.0.remap_glyphs(f)
274	}
275
276	fn tag(&self) -> Tag {
277		Self::TAG
278	}
279
280	fn compile(&mut self, font: &mut Font) -> Result<Vec<u8>> {
281		self.0
282			.compile_with(font, |head| Box::new(Bhed(head.clone())))
283	}
284
285	fn clone_table(&self) -> Box<dyn Table> {
286		Box::new(self.clone())
287	}
288}
289
290impl TableXml for Bhed {
291	fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font) -> Result<()> {
292		self.0.to_xml(writer, font)
293	}
294
295	fn from_xml(&mut self, element: &Element, font: &mut Font) -> Result<()> {
296		self.0.from_xml(element, font)
297	}
298}
299
300#[cfg(test)]
301mod tests {
302	use super::*;
303
304	#[test]
305	fn format_matches_upstream() {
306		crate::sstruct::tests::check(Head::FORMAT_NAME, Head::FIELDS);
307	}
308}