Skip to main content

fontoxide_ttlib/tables/
gvar.rs

1//! `gvar` and `cvar`: Glyph Variations and CVT Variations tables
2//! (`fontTools.ttLib.tables._g_v_a_r`, `_c_v_a_r`).
3
4use std::collections::HashMap;
5
6use fontoxide_misc::Tag;
7use fontoxide_misc::text_tools::{parse_int_radix, safe_eval_int};
8use fontoxide_misc::xml_reader::Element;
9use fontoxide_misc::xml_writer::XmlWriter;
10
11use crate::sstruct::eval;
12use crate::table::{Table, TableType, TableXml};
13use crate::tables::glyf::{Glyf, Glyph};
14use crate::tables::tuple_variation::{
15	TupleVariation, compile_shared_tuples, compile_tuple_variation_store, decompile_shared_tuples,
16	decompile_tuple_variation_store,
17};
18use crate::tables::{Cvt, Fvar};
19use crate::{Error, Font, Result};
20
21const FVAR: Tag = Tag::new(b"fvar");
22
23fn ushort(v: i64, name: &str) -> Result<[u8; 2]> {
24	u16::try_from(v)
25		.map(u16::to_be_bytes)
26		.map_err(|_| Error::Struct(format!("'H' format requires 0 <= number <= 65535 ({name})")))
27}
28
29fn ulong(v: usize) -> Result<[u8; 4]> {
30	u32::try_from(v)
31		.map(u32::to_be_bytes)
32		.map_err(|_| Error::Struct("'I' format requires 0 <= number <= 4294967295".into()))
33}
34
35fn be16(data: &[u8], at: usize) -> Result<u16> {
36	data.get(at..at + 2)
37		.map(|b| u16::from_be_bytes([b[0], b[1]]))
38		.ok_or_else(|| Error::Struct("unpack requires a buffer of 2 bytes".into()))
39}
40
41fn be32(data: &[u8], at: usize) -> Result<u32> {
42	data.get(at..at + 4)
43		.map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
44		.ok_or_else(|| Error::Struct("unpack requires a buffer of 4 bytes".into()))
45}
46
47fn fvar_axis_tags(font: &mut Font) -> Result<Vec<String>> {
48	Ok(font
49		.require::<Fvar>()?
50		.axes
51		.iter()
52		.map(|a| a.tag_text())
53		.collect())
54}
55
56/// The number of points of a glyph including the four phantom points
57/// (`getNumPoints_`).
58fn num_points(glyph: &Glyph) -> usize {
59	if glyph.is_composite() {
60		glyph.components.len() + 4
61	} else {
62		glyph.coordinates.len() + 4
63	}
64}
65
66fn glyph_points(font: &mut Font, gid: u32, extended: bool) -> Result<usize> {
67	let order = font.glyph_order()?;
68	let glyf = font.require_locked::<Glyf>(extended)?;
69	let glyph = glyf
70		.glyphs
71		.get(&gid)
72		.ok_or_else(|| Error::ttlib(format!("KeyError: {:?}", order.name(gid))))?;
73	Ok(num_points(glyph))
74}
75
76/// The size of the header, with its glyph count: 16 bits in `gvar`, 24 bits in `GVAR`.
77fn header_size(extended: bool) -> usize {
78	if extended { 21 } else { 20 }
79}
80
81/// Glyph Variations table (`table__g_v_a_r`).
82///
83/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/gvar>.
84#[derive(Debug, Clone, PartialEq)]
85pub struct Gvar {
86	/// `version`.
87	pub version: i64,
88	/// `reserved`.
89	pub reserved: i64,
90	/// The number of axes, used when there is no `fvar` (`axisCount`).
91	pub axis_count: i64,
92	/// The variations of each glyph, in the order fontTools' dict keeps them
93	/// (`variations`, keyed by glyph name there).
94	pub variations: Vec<(u32, Vec<TupleVariation>)>,
95	/// Whether the TTX numbered the axes, which it does without `fvar`.
96	pub numeric_axis_tags: bool,
97	/// Whether this is `GVAR`, the beyond-64k companion of the table.
98	pub extended: bool,
99}
100
101impl Default for Gvar {
102	fn default() -> Self {
103		Gvar {
104			version: 1,
105			reserved: 0,
106			axis_count: 0,
107			variations: Vec::new(),
108			numeric_axis_tags: false,
109			extended: false,
110		}
111	}
112}
113
114impl Gvar {
115	/// The axis tags: from `fvar`, or numbers (`getAxisTags_`).
116	fn axis_tags(&self, font: &mut Font) -> Result<Vec<String>> {
117		if font.contains(FVAR) {
118			return fvar_axis_tags(font);
119		}
120		Ok((0..self.axis_count.max(0)).map(|i| i.to_string()).collect())
121	}
122
123	/// The variations of a glyph.
124	pub fn get(&self, gid: u32) -> Option<&[TupleVariation]> {
125		self.variations
126			.iter()
127			.find(|(g, _)| *g == gid)
128			.map(|(_, v)| v.as_slice())
129	}
130
131	/// Sets the variations of a glyph, keeping its place if it has some.
132	pub fn set(&mut self, gid: u32, variations: Vec<TupleVariation>) {
133		match self.variations.iter_mut().find(|(g, _)| *g == gid) {
134			Some(entry) => entry.1 = variations,
135			None => self.variations.push((gid, variations)),
136		}
137	}
138}
139
140/// `compileOffsets_`: the packed offsets, as short offsets (halved) if they fit, and the
141/// table format that goes in the flags of the header: 0 for short, 1 for long.
142pub fn compile_offsets(offsets: &[usize]) -> Result<(Vec<u8>, u16)> {
143	let long = offsets.iter().any(|&o| o > 0xFFFF * 2);
144	let mut packed = Vec::with_capacity(offsets.len() * if long { 4 } else { 2 });
145	for &o in offsets {
146		if long {
147			packed.extend_from_slice(&ulong(o)?);
148		} else {
149			packed.extend_from_slice(&((o >> 1) as u16).to_be_bytes());
150		}
151	}
152	Ok((packed, u16::from(long)))
153}
154
155/// `decompileOffsets_`: the offsets of `glyph_count` glyphs and the end, as far as `data`
156/// has them.
157pub fn decompile_offsets(data: &[u8], table_format: u16, glyph_count: usize) -> Vec<usize> {
158	let count = glyph_count + 1;
159	if table_format == 0 {
160		// In the short format, offsets need to be multiplied by 2.
161		data.as_chunks::<2>()
162			.0
163			.iter()
164			.take(count)
165			.map(|&b| 2 * u16::from_be_bytes(b) as usize)
166			.collect()
167	} else {
168		data.as_chunks::<4>()
169			.0
170			.iter()
171			.take(count)
172			.map(|&b| u32::from_be_bytes(b) as usize)
173			.collect()
174	}
175}
176
177/// `compileGlyph_`.
178fn compile_glyph(
179	variations: &[TupleVariation],
180	axis_tags: &[String],
181	shared: &HashMap<Vec<u8>, usize>,
182	extended: bool,
183	optimize_size: bool,
184) -> Result<Vec<u8>> {
185	let (count, tuples, data) =
186		compile_tuple_variation_store(variations, axis_tags, shared, true, optimize_size)?;
187	if count == 0 {
188		return Ok(Vec::new());
189	}
190	let offset_size = if extended { 3 } else { 2 };
191	let offset_to_data = 2 + offset_size + tuples.len();
192	let mut out = Vec::with_capacity(offset_to_data + data.len() + 1);
193	let int = |v: usize| {
194		u16::try_from(v)
195			.map(u16::to_be_bytes)
196			.map_err(|_| Error::value("OverflowError: int too big to convert"))
197	};
198	out.extend_from_slice(&int(count as usize)?);
199	if extended {
200		if offset_to_data > 0xFF_FFFF {
201			return Err(Error::value("OverflowError: int too big to convert"));
202		}
203		out.extend_from_slice(&(offset_to_data as u32).to_be_bytes()[1..]);
204	} else {
205		out.extend_from_slice(&int(offset_to_data)?);
206	}
207	out.extend(tuples);
208	let odd = (offset_to_data + data.len()) % 2 != 0;
209	out.extend(data);
210	if odd {
211		out.push(0);
212	}
213	Ok(out)
214}
215
216impl TableType for Gvar {
217	const TAG: Tag = Tag::new(b"gvar");
218	const COMPANION: Option<Tag> = Some(Tag::new(b"GVAR"));
219
220	fn decompile(data: &[u8], font: &mut Font) -> Result<Self> {
221		Self::decompile_as(Self::TAG, data, font)
222	}
223
224	fn new_as(tag: Tag) -> Self {
225		Gvar {
226			extended: tag == Tag::new(b"GVAR"),
227			..Default::default()
228		}
229	}
230
231	fn decompile_as(tag: Tag, data: &[u8], font: &mut Font) -> Result<Self> {
232		let extended = tag == Tag::new(b"GVAR");
233		// What follows the glyph count moves with its size.
234		let gid_size = if extended { 3 } else { 2 };
235		let tail = 12 + gid_size;
236		let order = font.glyph_order()?;
237		let version = be16(data, 0)? as i64;
238		let reserved = be16(data, 2)? as i64;
239		let axis_count = be16(data, 4)? as i64;
240		let shared_count = be16(data, 6)? as usize;
241		let shared_offset = be32(data, 8)? as usize;
242		let glyph_count = data
243			.get(12..tail)
244			.map_or(0, |b| b.iter().fold(0usize, |a, &x| a << 8 | x as usize));
245		let flags = be16(data, tail)?;
246		let data_offset = be32(data, tail + 2)? as usize;
247		let mut table = Gvar {
248			version,
249			reserved,
250			axis_count,
251			extended,
252			..Default::default()
253		};
254		let axis_tags = table.axis_tags(font)?;
255		if order.len() != glyph_count {
256			return Err(Error::Assertion(format!(
257				"({}, {glyph_count})",
258				order.len()
259			)));
260		}
261		if axis_tags.len() as i64 != axis_count {
262			return Err(Error::Assertion(format!(
263				"({}, {axis_count})",
264				axis_tags.len()
265			)));
266		}
267		let shared = decompile_shared_tuples(&axis_tags, shared_count, data, shared_offset)?;
268		font.require_locked::<Glyf>(extended)?;
269		let offsets = decompile_offsets(
270			data.get(header_size(extended)..).unwrap_or_default(),
271			flags & 1,
272			glyph_count,
273		);
274		for gid in 0..glyph_count {
275			let (Some(&o0), Some(&o1)) = (offsets.get(gid), offsets.get(gid + 1)) else {
276				return Err(Error::ttlib("IndexError: array index out of range"));
277			};
278			let from = (data_offset + o0).min(data.len());
279			let to = (data_offset + o1).min(data.len()).max(from);
280			let glyph_data = &data[from..to];
281			let variations = if glyph_data.is_empty() {
282				Vec::new()
283			} else {
284				let points = glyph_points(font, gid as u32, extended)?;
285				if glyph_data.len() < 2 + gid_size {
286					Vec::new()
287				} else {
288					let count = u16::from_be_bytes([glyph_data[0], glyph_data[1]]);
289					let offset = glyph_data[2..2 + gid_size]
290						.iter()
291						.fold(0usize, |a, &x| a << 8 | x as usize);
292					decompile_tuple_variation_store(
293						"gvar",
294						&axis_tags,
295						count,
296						points,
297						Some(&shared),
298						glyph_data,
299						2 + gid_size,
300						offset,
301					)?
302				}
303			};
304			table.variations.push((gid as u32, variations));
305		}
306		Ok(table)
307	}
308}
309
310impl Table for Gvar {
311	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
312		for (g, _) in &mut self.variations {
313			*g = f(*g)?;
314		}
315		self.variations.sort_by_key(|(g, _)| *g);
316		Ok(())
317	}
318
319	fn tag(&self) -> Tag {
320		Font::locked_tag::<Self>(self.extended)
321	}
322
323	fn compile(&mut self, font: &mut Font) -> Result<Vec<u8>> {
324		let axis_tags = self.axis_tags(font)?;
325		let shared = compile_shared_tuples(
326			&axis_tags,
327			self.variations.iter().flat_map(|(_, v)| v.iter()),
328		)?;
329		let indices: HashMap<Vec<u8>, usize> = shared
330			.iter()
331			.enumerate()
332			.map(|(i, c)| (c.clone(), i))
333			.collect();
334		let shared_size: usize = shared.iter().map(Vec::len).sum();
335		let order = font.glyph_order()?;
336		font.require_locked::<Glyf>(self.extended)?;
337		let by_gid: HashMap<u32, &Vec<TupleVariation>> =
338			self.variations.iter().map(|(g, v)| (*g, v)).collect();
339		let optimize_size = !font.optimize_font_speed;
340		let mut glyphs = Vec::with_capacity(order.len());
341		for gid in 0..order.len() as u32 {
342			glyphs.push(match by_gid.get(&gid) {
343				Some(v) if !v.is_empty() => {
344					compile_glyph(v, &axis_tags, &indices, self.extended, optimize_size)?
345				}
346				_ => Vec::new(),
347			});
348		}
349		let mut offsets = Vec::with_capacity(glyphs.len() + 1);
350		let mut at = 0usize;
351		for g in &glyphs {
352			offsets.push(at);
353			at += g.len();
354		}
355		offsets.push(at);
356		let (packed, table_format) = compile_offsets(&offsets)?;
357		let shared_offset = header_size(self.extended) + packed.len();
358		let mut out = Vec::new();
359		out.extend_from_slice(&ushort(self.version, "version")?);
360		out.extend_from_slice(&ushort(self.reserved, "reserved")?);
361		out.extend_from_slice(&ushort(axis_tags.len() as i64, "axisCount")?);
362		out.extend_from_slice(&ushort(shared.len() as i64, "sharedTupleCount")?);
363		out.extend_from_slice(&ulong(shared_offset)?);
364		if self.extended {
365			if glyphs.len() > 0xFF_FFFF {
366				return Err(Error::value("OverflowError: int too big to convert"));
367			}
368			out.extend_from_slice(&(glyphs.len() as u32).to_be_bytes()[1..]);
369		} else {
370			out.extend_from_slice(
371				&u16::try_from(glyphs.len())
372					.map_err(|_| Error::value("OverflowError: int too big to convert"))?
373					.to_be_bytes(),
374			);
375		}
376		out.extend_from_slice(&table_format.to_be_bytes());
377		out.extend_from_slice(&ulong(shared_offset + shared_size)?);
378		out.extend(packed);
379		for s in shared {
380			out.extend(s);
381		}
382		for g in glyphs {
383			out.extend(g);
384		}
385		Ok(out)
386	}
387
388	fn clone_table(&self) -> Box<dyn Table> {
389		Box::new(self.clone())
390	}
391}
392
393impl TableXml for Gvar {
394	fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font) -> Result<()> {
395		writer.simpletag("version", &[("value", &self.version)]);
396		writer.newline();
397		writer.simpletag("reserved", &[("value", &self.reserved)]);
398		writer.newline();
399		if !font.contains(FVAR) {
400			writer.simpletag("axisCount", &[("value", &self.axis_count)]);
401			writer.newline();
402		}
403		let axis_tags = self.axis_tags(font)?;
404		let order = font.glyph_order()?;
405		let mut names: Vec<&String> = order.names().iter().collect();
406		names.sort();
407		for name in names {
408			let Some(variations) = order.id(name).and_then(|gid| self.get(gid)) else {
409				continue;
410			};
411			if variations.is_empty() {
412				continue;
413			}
414			writer.begintag("glyphVariations", &[("glyph", name)]);
415			writer.newline();
416			for v in variations {
417				v.to_xml(writer, &axis_tags);
418			}
419			writer.endtag("glyphVariations");
420			writer.newline();
421		}
422		Ok(())
423	}
424
425	fn from_xml(&mut self, element: &Element, font: &mut Font) -> Result<()> {
426		let value = || -> Result<i64> {
427			let v = element
428				.attr("value")
429				.ok_or_else(|| Error::ttx("KeyError: 'value'"))?;
430			eval(v)?
431				.as_int()
432				.and_then(|i| i64::try_from(i).ok())
433				.ok_or_else(|| Error::value(format!("invalid value: {v:?}")))
434		};
435		match element.name.as_str() {
436			"version" => self.version = value()?,
437			"reserved" => self.reserved = value()?,
438			"axisCount" => {
439				self.axis_count = value()?;
440				self.numeric_axis_tags = true;
441			}
442			"glyphVariations" => {
443				let name = element
444					.attr("glyph")
445					.ok_or_else(|| Error::ttx("KeyError: 'glyph'"))?;
446				let gid = font.glyph_id(name)?;
447				let points = glyph_points(font, gid, self.extended)?;
448				let mut variations = Vec::new();
449				for t in element.elements().filter(|e| e.name == "tuple") {
450					let mut v = TupleVariation::new(points);
451					for child in t.elements() {
452						v.from_xml(child)?;
453					}
454					if self.numeric_axis_tags {
455						v.axes = v
456							.axes
457							.into_iter()
458							.map(|(axis, region)| {
459								let n = safe_eval_int(&axis).ok_or_else(|| {
460									Error::value(format!("malformed node or string: {axis:?}"))
461								})?;
462								Ok((n.to_string(), region))
463							})
464							.collect::<Result<_>>()?;
465					}
466					variations.push(v);
467				}
468				self.set(gid, variations);
469			}
470			_ => {}
471		}
472		Ok(())
473	}
474}
475
476/// CVT Variations table (`table__c_v_a_r`).
477///
478/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/cvar>.
479#[derive(Debug, Clone, PartialEq)]
480pub struct Cvar {
481	/// `majorVersion`.
482	pub major_version: i64,
483	/// `minorVersion`.
484	pub minor_version: i64,
485	/// The variations of the control values (`variations`).
486	pub variations: Vec<TupleVariation>,
487}
488
489impl Default for Cvar {
490	fn default() -> Self {
491		Cvar {
492			major_version: 1,
493			minor_version: 0,
494			variations: Vec::new(),
495		}
496	}
497}
498
499fn cvt_count(font: &mut Font) -> Result<usize> {
500	Ok(font.require::<Cvt>()?.values.len())
501}
502
503impl Cvar {
504	/// Compiles the table, with the point numbers shared between the variations
505	/// if `use_shared_points` (`compile(ttFont, useSharedPoints)`).
506	pub fn compile_with(&self, font: &mut Font, use_shared_points: bool) -> Result<Vec<u8>> {
507		let variations: Vec<TupleVariation> = self
508			.variations
509			.iter()
510			.filter(|v| v.has_impact())
511			.cloned()
512			.collect();
513		cvt_count(font)?;
514		let axis_tags = fvar_axis_tags(font)?;
515		let (count, tuples, data) = compile_tuple_variation_store(
516			&variations,
517			&axis_tags,
518			&HashMap::new(),
519			use_shared_points,
520			true,
521		)?;
522		let mut out = Vec::new();
523		out.extend_from_slice(&ushort(self.major_version, "majorVersion")?);
524		out.extend_from_slice(&ushort(self.minor_version, "minorVersion")?);
525		out.extend_from_slice(&ushort(count as i64, "tupleVariationCount")?);
526		out.extend_from_slice(&ushort(8 + tuples.len() as i64, "offsetToData")?);
527		out.extend(tuples);
528		out.extend(data);
529		Ok(out)
530	}
531}
532
533impl TableType for Cvar {
534	const TAG: Tag = Tag::new(b"cvar");
535
536	fn decompile(data: &[u8], font: &mut Font) -> Result<Self> {
537		let axis_tags = fvar_axis_tags(font)?;
538		let major = be16(data, 0)? as i64;
539		let minor = be16(data, 2)? as i64;
540		let count = be16(data, 4)?;
541		let offset = be16(data, 6)? as usize;
542		if major != 1 {
543			return Err(Error::Assertion(major.to_string()));
544		}
545		let points = cvt_count(font)?;
546		let variations = decompile_tuple_variation_store(
547			"cvar", &axis_tags, count, points, None, data, 8, offset,
548		)?;
549		Ok(Cvar {
550			major_version: major,
551			minor_version: minor,
552			variations,
553		})
554	}
555}
556
557impl Table for Cvar {
558	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
559		let _ = f;
560		Ok(())
561	}
562
563	fn tag(&self) -> Tag {
564		Self::TAG
565	}
566
567	fn compile(&mut self, font: &mut Font) -> Result<Vec<u8>> {
568		self.compile_with(font, false)
569	}
570
571	fn clone_table(&self) -> Box<dyn Table> {
572		Box::new(self.clone())
573	}
574}
575
576impl TableXml for Cvar {
577	fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font) -> Result<()> {
578		let axis_tags = fvar_axis_tags(font)?;
579		writer.simpletag(
580			"version",
581			&[
582				("major", &self.major_version),
583				("minor", &self.minor_version),
584			],
585		);
586		writer.newline();
587		for v in &self.variations {
588			v.to_xml(writer, &axis_tags);
589		}
590		Ok(())
591	}
592
593	fn from_xml(&mut self, element: &Element, font: &mut Font) -> Result<()> {
594		match element.name.as_str() {
595			"version" => {
596				let int = |name: &str, default: &str| -> Result<i64> {
597					let s = element.attr(name).unwrap_or(default);
598					parse_int_radix(s, 10)
599						.and_then(|v| i64::try_from(v).ok())
600						.ok_or_else(|| {
601							Error::value(format!("invalid literal for int() with base 10: {s:?}"))
602						})
603				};
604				self.major_version = int("major", "1")?;
605				self.minor_version = int("minor", "0")?;
606			}
607			"tuple" => {
608				let mut v = TupleVariation::new(cvt_count(font)?);
609				for child in element.elements() {
610					v.from_xml(child)?;
611				}
612				self.variations.push(v);
613			}
614			_ => {}
615		}
616		Ok(())
617	}
618}