Skip to main content

fontoxide_ttlib/tables/
fpgm.rs

1//! `fpgm` and `prep`: the Font Program and the Control Value Program
2//! (`fontTools.ttLib.tables._f_p_g_m`, `_p_r_e_p`).
3
4use fontoxide_misc::Tag;
5use fontoxide_misc::xml_reader::Element;
6use fontoxide_misc::xml_writer::XmlWriter;
7
8use crate::table::{Table, TableType, TableXml};
9use crate::tables::tt_program::Program;
10use crate::{Error, Font, Result};
11
12macro_rules! program_table {
13	($(#[$meta:meta])* $name:ident, $tag:literal, $class:literal) => {
14		$(#[$meta])*
15		#[derive(Debug, Clone, Default, PartialEq, Eq)]
16		pub struct $name {
17			/// The program (`program`), if set.
18			pub program: Option<Program>,
19		}
20
21		impl $name {
22			/// Whether the table has no program or an empty one (`not __bool__`).
23			pub fn is_empty(&self) -> bool {
24				self.program.as_ref().is_none_or(Program::is_empty)
25			}
26		}
27
28		impl TableType for $name {
29			const TAG: Tag = Tag::new($tag);
30
31			fn decompile(data: &[u8], _font: &mut Font) -> Result<Self> {
32				Ok($name {
33					program: Some(Program::from_bytecode(data)),
34				})
35			}
36		}
37
38		impl Table for $name {
39			fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
40				let _ = f;
41				Ok(())
42			}
43
44			fn tag(&self) -> Tag {
45				Self::TAG
46			}
47
48			fn compile(&mut self, _font: &mut Font) -> Result<Vec<u8>> {
49				Ok(self
50					.program
51					.as_ref()
52					.map(|p| p.bytecode.clone())
53					.unwrap_or_default())
54			}
55
56			fn clone_table(&self) -> Box<dyn Table> {
57				Box::new(self.clone())
58			}
59		}
60
61		impl TableXml for $name {
62			fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font) -> Result<()> {
63				let program = self.program.as_ref().ok_or_else(|| {
64					Error::ttlib(concat!(
65						"AttributeError: '",
66						$class,
67						"' object has no attribute 'program'"
68					))
69				})?;
70				program.to_xml_with(writer, font.disassemble_instructions);
71				Ok(())
72			}
73
74			fn from_xml(&mut self, element: &Element, _font: &mut Font) -> Result<()> {
75				self.program = Some(Program::from_xml(element)?);
76				Ok(())
77			}
78		}
79	};
80}
81
82program_table!(
83	/// Font Program table (`table__f_p_g_m`): functions used by the glyph
84	/// programs, run once when the font is first used.
85	///
86	/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/fpgm>.
87	Fpgm,
88	b"fpgm",
89	"table__f_p_g_m"
90);
91
92program_table!(
93	/// Control Value Program table (`table__p_r_e_p`): run whenever the size
94	/// or transformation changes.
95	///
96	/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/prep>.
97	Prep,
98	b"prep",
99	"table__p_r_e_p"
100);