use fontoxide_misc::Tag;
use fontoxide_misc::xml_reader::Element;
use fontoxide_misc::xml_writer::XmlWriter;
use crate::binary::WriteBytes;
use crate::sstruct::{I32, U16, eval};
use crate::table::{Table, TableType};
use crate::{Error, Font, Result};
crate::sstruct! {
pub struct MaxpFormat05 = "maxpFormat_0_5" {
pub table_version: i32 = "tableVersion" as I32,
pub num_glyphs: u16 = "numGlyphs" as U16,
}
}
crate::sstruct! {
pub struct MaxpV1 = "maxpFormat_1_0_add" {
pub max_points: u16 = "maxPoints" as U16,
pub max_contours: u16 = "maxContours" as U16,
pub max_composite_points: u16 = "maxCompositePoints" as U16,
pub max_composite_contours: u16 = "maxCompositeContours" as U16,
pub max_zones: u16 = "maxZones" as U16,
pub max_twilight_points: u16 = "maxTwilightPoints" as U16,
pub max_storage: u16 = "maxStorage" as U16,
pub max_function_defs: u16 = "maxFunctionDefs" as U16,
pub max_instruction_defs: u16 = "maxInstructionDefs" as U16,
pub max_stack_elements: u16 = "maxStackElements" as U16,
pub max_size_of_instructions: u16 = "maxSizeOfInstructions" as U16,
pub max_component_elements: u16 = "maxComponentElements" as U16,
pub max_component_depth: u16 = "maxComponentDepth" as U16,
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Maxp {
pub table_version: u32,
pub num_glyphs: u32,
pub v1: MaxpV1,
pub extended: bool,
}
const VERSION_0_5: u32 = 0x0000_5000;
impl TableType for Maxp {
const TAG: Tag = Tag::new(b"maxp");
const COMPANION: Option<Tag> = Some(Tag::new(b"MAXP"));
fn decompile(data: &[u8], font: &mut Font) -> Result<Self> {
Self::decompile_as(Self::TAG, data, font)
}
fn new_as(tag: Tag) -> Self {
Maxp {
extended: tag == Tag::new(b"MAXP"),
..Default::default()
}
}
fn decompile_as(tag: Tag, data: &[u8], _font: &mut Font) -> Result<Self> {
let extended = tag == Tag::new(b"MAXP");
let header_size = if extended { 7 } else { 6 };
let int = |bytes: &[u8]| bytes.iter().fold(0u64, |acc, &b| acc << 8 | b as u64);
let table_version = int(&data[..data.len().min(4)]) as u32;
let num_glyphs = int(data.get(4..data.len().min(header_size)).unwrap_or_default()) as u32;
let mut rest = data.get(header_size..).unwrap_or_default();
let mut v1 = MaxpV1::default();
if table_version != VERSION_0_5 {
let (parsed, r) = MaxpV1::unpack2(rest)?;
v1 = parsed;
rest = r;
}
if !rest.is_empty() {
return Err(Error::Assertion("len(data) == 0".into()));
}
Ok(Maxp {
table_version,
num_glyphs,
v1,
extended,
})
}
}
impl Table for Maxp {
fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
let _ = f;
Ok(())
}
fn tag(&self) -> Tag {
Font::locked_tag::<Self>(self.extended)
}
fn compile(&mut self, font: &mut Font) -> Result<Vec<u8>> {
font.insert(self.clone_table());
let glyf = Font::locked_tag::<crate::tables::Glyf>(self.extended);
if font.contains(glyf) && font.is_loaded(glyf) && font.recalc_bboxes {
self.recalc(font)?;
font.insert(self.clone_table());
}
self.num_glyphs = crate::binary::fit(font.glyph_order()?.len(), "numGlyphs")?;
if self.table_version != VERSION_0_5 {
self.table_version = 0x0001_0000;
}
let mut data = Vec::new();
data.put_u32(self.table_version);
if self.extended {
if self.num_glyphs > 0xFF_FFFF {
return Err(Error::value("OverflowError: int too big to convert"));
}
data.extend_from_slice(&self.num_glyphs.to_be_bytes()[1..]);
} else {
data.put_u16(crate::binary::fit(self.num_glyphs, "numGlyphs")?);
}
if self.table_version == 0x0001_0000 {
self.v1.pack(&mut data)?;
}
Ok(data)
}
fn to_xml(&self, writer: &mut XmlWriter, _font: &mut Font) -> Result<()> {
let v1 = self.table_version != VERSION_0_5;
if v1 {
writer.comment("Most of this table will be recalculated by the compiler");
writer.newline();
}
let version = format!("{:#x}", self.table_version);
writer.simpletag("tableVersion", &[("value", &version)]);
writer.newline();
writer.simpletag("numGlyphs", &[("value", &self.num_glyphs)]);
writer.newline();
if v1 {
for (name, value) in self.v1.values() {
writer.simpletag(name, &[("value", &value)]);
writer.newline();
}
}
Ok(())
}
fn from_xml(&mut self, element: &Element, _font: &mut Font) -> Result<()> {
let name = element.name.as_str();
let value = element
.attr("value")
.ok_or_else(|| Error::ttx(format!("missing 'value' on <{name}>")))?;
let lit = eval(value)?;
match name {
"tableVersion" => {
let v = lit
.as_int()
.ok_or_else(|| Error::value("invalid tableVersion"))?;
self.table_version = crate::binary::fit(v, name)?;
}
"numGlyphs" => {
let v = lit
.as_int()
.ok_or_else(|| Error::value("invalid numGlyphs"))?;
self.num_glyphs = crate::binary::fit(v, name)?;
}
_ => {
if !self.v1.set_literal(name, &lit)? {
return Err(Error::ttx(format!("unknown 'maxp' field: {name}")));
}
}
}
Ok(())
}
fn clone_table(&self) -> Box<dyn Table> {
Box::new(self.clone())
}
}
impl Maxp {
pub fn recalc(&mut self, font: &mut Font) -> Result<()> {
crate::tables::metrics::recalc_maxp(self, font)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn formats_match_upstream() {
crate::sstruct::tests::check(MaxpFormat05::FORMAT_NAME, MaxpFormat05::FIELDS);
crate::sstruct::tests::check(MaxpV1::FORMAT_NAME, MaxpV1::FIELDS);
}
}