Skip to main content

fontoxide_ttlib/tables/
fvar.rs

1//! `fvar`: Font Variations table (`fontTools.ttLib.tables._f_v_a_r`).
2
3use std::collections::BTreeMap;
4
5use fontoxide_misc::Tag;
6use fontoxide_misc::fixed_tools::{float_to_fixed, float_to_fixed_to_str, str_to_fixed_to_float};
7use fontoxide_misc::xml_reader::Element;
8use fontoxide_misc::xml_writer::XmlWriter;
9
10use crate::binary::{Reader, WriteBytes, fit};
11use crate::sstruct::{Bytes, F16Dot16, U16, U32, eval};
12use crate::table::{Table, TableType, TableXml};
13use crate::tables::Name;
14use crate::{Error, Font, Result};
15
16crate::sstruct! {
17	/// The `fvar` header (`FVAR_HEADER_FORMAT`).
18	pub struct FvarHeader = "FVAR_HEADER_FORMAT" {
19		/// 0x00010000.
20		pub version: u32 = "version" as U32,
21		/// Offset to the axis records.
22		pub offset_to_data: u16 = "offsetToData" as U16,
23		/// 2.
24		pub count_size_pairs: u16 = "countSizePairs" as U16,
25		/// Number of axes.
26		pub axis_count: u16 = "axisCount" as U16,
27		/// Size of an axis record.
28		pub axis_size: u16 = "axisSize" as U16,
29		/// Number of named instances.
30		pub instance_count: u16 = "instanceCount" as U16,
31		/// Size of an instance record.
32		pub instance_size: u16 = "instanceSize" as U16,
33	}
34}
35
36crate::sstruct! {
37	/// A variation axis (`Axis`, `FVAR_AXIS_FORMAT`).
38	pub struct Axis = "FVAR_AXIS_FORMAT" {
39		/// Axis tag.
40		pub axis_tag: [u8; 4] = "axisTag" as Bytes<4>,
41		/// Minimum value.
42		pub min_value: f64 = "minValue" as F16Dot16,
43		/// Default value.
44		pub default_value: f64 = "defaultValue" as F16Dot16,
45		/// Maximum value.
46		pub max_value: f64 = "maxValue" as F16Dot16,
47		/// Flags; bit 0 hides the axis.
48		pub flags: u16 = "flags" as U16,
49		/// Name ID of the axis name.
50		pub axis_name_id: u16 = "axisNameID" as U16,
51	}
52}
53
54crate::sstruct! {
55	/// The fixed part of a named instance (`FVAR_INSTANCE_FORMAT`).
56	pub struct InstanceHeader = "FVAR_INSTANCE_FORMAT" {
57		/// Name ID of the subfamily name.
58		pub subfamily_name_id: u16 = "subfamilyNameID" as U16,
59		/// Flags.
60		pub flags: u16 = "flags" as U16,
61	}
62}
63
64impl Axis {
65	/// An axis with fontTools' defaults (`Axis()`): range −1…1, default 0.
66	pub fn new(tag: Tag) -> Self {
67		Axis {
68			axis_tag: tag.0,
69			min_value: -1.0,
70			default_value: 0.0,
71			max_value: 1.0,
72			flags: 0,
73			axis_name_id: 0,
74		}
75	}
76
77	/// The axis tag.
78	pub fn tag(&self) -> Tag {
79		Tag(self.axis_tag)
80	}
81
82	/// The tag as fontTools holds it after unpacking: a `str` if ASCII.
83	pub fn tag_text(&self) -> String {
84		crate::sstruct::bytes_to_py_str(&self.axis_tag)
85	}
86
87	/// Writes the axis to TTX, after a comment with its name from `names`
88	/// (`toXML`).
89	pub fn to_xml(&self, writer: &mut XmlWriter, names: Option<&Name>) {
90		if let Some(name) = names.and_then(|n| n.get_debug_name(self.axis_name_id)) {
91			writer.newline();
92			writer.comment(&name);
93			writer.newline();
94		}
95		writer.begintag("Axis", &[]);
96		writer.newline();
97		for (tag, value) in [
98			("AxisTag", self.tag_text()),
99			("Flags", format!("0x{:X}", self.flags)),
100			("MinValue", float_to_fixed_to_str(self.min_value, 16)),
101			(
102				"DefaultValue",
103				float_to_fixed_to_str(self.default_value, 16),
104			),
105			("MaxValue", float_to_fixed_to_str(self.max_value, 16)),
106			("AxisNameID", self.axis_name_id.to_string()),
107		] {
108			writer.begintag(tag, &[]);
109			writer.write(&value);
110			writer.endtag(tag);
111			writer.newline();
112		}
113		writer.endtag("Axis");
114		writer.newline();
115	}
116
117	/// Reads an `<Axis>` element (`fromXML`).
118	pub fn from_xml(element: &Element) -> Result<Self> {
119		let mut axis = Axis::new(Tag::default());
120		axis.axis_tag = [0; 4];
121		for e in element.elements() {
122			let value = e.text();
123			let fixed = || {
124				str_to_fixed_to_float(&value, 16).ok_or_else(|| {
125					Error::value(format!("could not convert string to float: {value:?}"))
126				})
127			};
128			let int = || -> Result<u16> {
129				let v = eval(&value)?
130					.as_int()
131					.ok_or_else(|| Error::value(format!("invalid {}", e.name)))?;
132				fit(v, &e.name)
133			};
134			match e.name.as_str() {
135				"AxisTag" => {
136					// Packed as "4s": truncated or padded with NUL bytes.
137					let bytes = fontoxide_misc::py::latin1_encode(&value)
138						.ok_or_else(|| Error::value("'ascii' codec can't encode the axis tag"))?;
139					let mut tag = [0u8; 4];
140					for (d, b) in tag.iter_mut().zip(bytes) {
141						*d = b;
142					}
143					axis.axis_tag = tag;
144				}
145				"Flags" => axis.flags = int()?,
146				"MinValue" => axis.min_value = fixed()?,
147				"DefaultValue" => axis.default_value = fixed()?,
148				"MaxValue" => axis.max_value = fixed()?,
149				"AxisNameID" => axis.axis_name_id = int()?,
150				_ => {}
151			}
152		}
153		Ok(axis)
154	}
155}
156
157/// A named instance (`NamedInstance`).
158#[derive(Debug, Clone, PartialEq)]
159pub struct NamedInstance {
160	/// Name ID of the subfamily name.
161	pub subfamily_name_id: u16,
162	/// Name ID of the PostScript name, or 0xFFFF for none.
163	pub postscript_name_id: u16,
164	/// Flags.
165	pub flags: u16,
166	/// The location, by axis tag.
167	pub coordinates: BTreeMap<Tag, f64>,
168}
169
170impl Default for NamedInstance {
171	fn default() -> Self {
172		NamedInstance {
173			subfamily_name_id: 0,
174			postscript_name_id: 0xFFFF,
175			flags: 0,
176			coordinates: BTreeMap::new(),
177		}
178	}
179}
180
181impl NamedInstance {
182	/// Parses an instance record of the given axes (`decompile`); without the
183	/// trailing PostScript name ID, it is 0xFFFF.
184	pub fn decompile(data: &[u8], axis_tags: &[Tag]) -> Result<Self> {
185		let (header, _) = InstanceHeader::unpack2(data)?;
186		let mut instance = NamedInstance {
187			subfamily_name_id: header.subfamily_name_id,
188			flags: header.flags,
189			..Default::default()
190		};
191		let mut r = Reader::new(data);
192		r.seek(InstanceHeader::SIZE);
193		for &tag in axis_tags {
194			let value = r.i32()?;
195			instance.coordinates.insert(
196				tag,
197				fontoxide_misc::fixed_tools::fixed_to_float(value as i64, 16),
198			);
199		}
200		instance.postscript_name_id = if r.remaining() >= 2 { r.u16()? } else { 0xFFFF };
201		Ok(instance)
202	}
203
204	/// Appends the instance record for the given axes to `out` (`compile`).
205	pub fn compile(
206		&self,
207		axis_tags: &[Tag],
208		include_postscript_name: bool,
209		out: &mut Vec<u8>,
210	) -> Result<()> {
211		InstanceHeader {
212			subfamily_name_id: self.subfamily_name_id,
213			flags: self.flags,
214		}
215		.pack(out)?;
216		for tag in axis_tags {
217			let v = self.coordinates.get(tag).ok_or_else(|| {
218				Error::value(format!("named instance has no coordinate for '{tag}'"))
219			})?;
220			out.put_i32(fit(float_to_fixed(*v, 16), "coordinate")?);
221		}
222		if include_postscript_name {
223			out.put_u16(self.postscript_name_id);
224		}
225		Ok(())
226	}
227
228	/// Writes the instance to TTX, after comments with its names from `names`
229	/// (`toXML`).
230	pub fn to_xml(
231		&self,
232		writer: &mut XmlWriter,
233		names: Option<&Name>,
234		axes: &[Axis],
235	) -> Result<()> {
236		if let Some(name) = names.and_then(|n| n.get_debug_name(self.subfamily_name_id)) {
237			writer.newline();
238			writer.comment(&name);
239			writer.newline();
240		}
241		if let Some(ps) = names.and_then(|n| n.get_debug_name(self.postscript_name_id)) {
242			writer.comment(&format!("PostScript: {ps}"));
243			writer.newline();
244		}
245		let flags = format!("0x{:X}", self.flags);
246		if self.postscript_name_id == 0xFFFF {
247			writer.begintag(
248				"NamedInstance",
249				&[
250					("flags", &flags),
251					("subfamilyNameID", &self.subfamily_name_id),
252				],
253			);
254		} else {
255			writer.begintag(
256				"NamedInstance",
257				&[
258					("flags", &flags),
259					("subfamilyNameID", &self.subfamily_name_id),
260					("postscriptNameID", &self.postscript_name_id),
261				],
262			);
263		}
264		writer.newline();
265		for axis in axes {
266			let v = self.coordinates.get(&axis.tag()).ok_or_else(|| {
267				Error::value(format!(
268					"named instance has no coordinate for '{}'",
269					axis.tag()
270				))
271			})?;
272			let value = float_to_fixed_to_str(*v, 16);
273			writer.simpletag("coord", &[("axis", &axis.tag_text()), ("value", &value)]);
274			writer.newline();
275		}
276		writer.endtag("NamedInstance");
277		writer.newline();
278		Ok(())
279	}
280
281	/// Reads a `<NamedInstance>` element (`fromXML`).
282	pub fn from_xml(element: &Element) -> Result<Self> {
283		let int = |name: &str, default: Option<&str>| -> Result<u16> {
284			let text = element
285				.attr(name)
286				.or(default)
287				.ok_or_else(|| Error::ttx(format!("missing '{name}' on <NamedInstance>")))?;
288			let v = eval(text)?
289				.as_int()
290				.ok_or_else(|| Error::value(format!("invalid {name}")))?;
291			fit(v, name)
292		};
293		let mut instance = NamedInstance {
294			subfamily_name_id: int("subfamilyNameID", None)?,
295			flags: int("flags", Some("0"))?,
296			postscript_name_id: int("postscriptNameID", Some("0xFFFF"))?,
297			coordinates: BTreeMap::new(),
298		};
299		for e in element.elements().filter(|e| e.name == "coord") {
300			let value = e
301				.attr("value")
302				.ok_or_else(|| Error::ttx("missing 'value' on <coord>"))?;
303			let axis = e
304				.attr("axis")
305				.ok_or_else(|| Error::ttx("missing 'axis' on <coord>"))?;
306			let value = str_to_fixed_to_float(value, 16).ok_or_else(|| {
307				Error::value(format!("could not convert string to float: {value:?}"))
308			})?;
309			let tag = Tag::from_str_exact(axis)
310				.ok_or_else(|| Error::value(format!("invalid axis tag: {axis:?}")))?;
311			instance.coordinates.insert(tag, value);
312		}
313		Ok(instance)
314	}
315}
316
317/// Font Variations table (`table__f_v_a_r`).
318///
319/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/fvar>.
320#[derive(Debug, Clone, PartialEq, Default)]
321pub struct Fvar {
322	/// The axes.
323	pub axes: Vec<Axis>,
324	/// The named instances.
325	pub instances: Vec<NamedInstance>,
326}
327
328impl Fvar {
329	/// The axes as tag → (min, default, max) (`getAxes`).
330	pub fn get_axes(&self) -> BTreeMap<Tag, (f64, f64, f64)> {
331		self.axes
332			.iter()
333			.map(|a| (a.tag(), (a.min_value, a.default_value, a.max_value)))
334			.collect()
335	}
336
337	fn axis_tags(&self) -> Vec<Tag> {
338		self.axes.iter().map(Axis::tag).collect()
339	}
340}
341
342impl TableType for Fvar {
343	const TAG: Tag = Tag::new(b"fvar");
344
345	fn decompile(data: &[u8], _font: &mut Font) -> Result<Self> {
346		let header_data = data.get(..FvarHeader::SIZE).ok_or_else(|| {
347			Error::Struct(format!(
348				"unpack requires a buffer of {} bytes",
349				FvarHeader::SIZE
350			))
351		})?;
352		let (header, _) = FvarHeader::unpack2(header_data)?;
353		if header.version != 0x0001_0000 {
354			return Err(Error::ttlib(format!(
355				"unsupported 'fvar' version {:04x}",
356				header.version
357			)));
358		}
359		let slice = |pos: usize, size: usize| {
360			data.get(pos..(pos + size).min(data.len()))
361				.unwrap_or_default()
362		};
363		let mut fvar = Fvar::default();
364		let mut pos = header.offset_to_data as usize;
365		for _ in 0..header.axis_count {
366			let (axis, _) = Axis::unpack2(slice(pos, header.axis_size as usize))?;
367			fvar.axes.push(axis);
368			pos += header.axis_size as usize;
369		}
370		let axis_tags = fvar.axis_tags();
371		for _ in 0..header.instance_count {
372			fvar.instances.push(NamedInstance::decompile(
373				slice(pos, header.instance_size as usize),
374				&axis_tags,
375			)?);
376			pos += header.instance_size as usize;
377		}
378		Ok(fvar)
379	}
380}
381
382impl Table for Fvar {
383	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
384		let _ = f;
385		Ok(())
386	}
387
388	fn tag(&self) -> Tag {
389		Self::TAG
390	}
391
392	fn compile(&mut self, _font: &mut Font) -> Result<Vec<u8>> {
393		let include_postscript_names = self
394			.instances
395			.iter()
396			.any(|i| i.postscript_name_id != 0xFFFF);
397		let mut instance_size = InstanceHeader::SIZE + 4 * self.axes.len();
398		if include_postscript_names {
399			instance_size += 2;
400		}
401		let mut data = Vec::new();
402		FvarHeader {
403			version: 0x0001_0000,
404			offset_to_data: FvarHeader::SIZE as u16,
405			count_size_pairs: 2,
406			axis_count: fit(self.axes.len(), "axisCount")?,
407			axis_size: Axis::SIZE as u16,
408			instance_count: fit(self.instances.len(), "instanceCount")?,
409			instance_size: fit(instance_size, "instanceSize")?,
410		}
411		.pack(&mut data)?;
412		for axis in &self.axes {
413			axis.pack(&mut data)?;
414		}
415		let axis_tags = self.axis_tags();
416		for instance in &self.instances {
417			instance.compile(&axis_tags, include_postscript_names, &mut data)?;
418		}
419		Ok(data)
420	}
421
422	fn clone_table(&self) -> Box<dyn Table> {
423		Box::new(self.clone())
424	}
425}
426
427impl TableXml for Fvar {
428	fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font) -> Result<()> {
429		let names = font.get::<Name>()?.map(|n| n.clone());
430		for axis in &self.axes {
431			axis.to_xml(writer, names.as_ref());
432		}
433		for instance in &self.instances {
434			instance.to_xml(writer, names.as_ref(), &self.axes)?;
435		}
436		Ok(())
437	}
438
439	fn from_xml(&mut self, element: &Element, _font: &mut Font) -> Result<()> {
440		match element.name.as_str() {
441			"Axis" => self.axes.push(Axis::from_xml(element)?),
442			"NamedInstance" => self.instances.push(NamedInstance::from_xml(element)?),
443			_ => {}
444		}
445		Ok(())
446	}
447}
448
449#[cfg(test)]
450mod tests {
451	use super::*;
452
453	#[test]
454	fn formats_match_upstream() {
455		use crate::sstruct::tests::check;
456		check(FvarHeader::FORMAT_NAME, FvarHeader::FIELDS);
457		check(Axis::FORMAT_NAME, Axis::FIELDS);
458		check(InstanceHeader::FORMAT_NAME, InstanceHeader::FIELDS);
459	}
460}