Skip to main content

fontoxide_ttlib/tables/
post.rs

1//! `post`: PostScript table (`fontTools.ttLib.tables._p_o_s_t`).
2
3use std::collections::{BTreeMap, HashMap, HashSet};
4
5use fontoxide_misc::Tag;
6use fontoxide_misc::xml_reader::Element;
7use fontoxide_misc::xml_writer::XmlWriter;
8
9use crate::binary::{Reader, WriteBytes};
10use crate::generated::standard_glyph_order::STANDARD_GLYPH_ORDER;
11use crate::sstruct::{F16Dot16, I16, U32, eval};
12use crate::table::{Table, TableType, TableXml, read_hex};
13use crate::{Error, Font, Result};
14
15crate::sstruct! {
16	/// The fixed part of the `post` table (`postFormat`).
17	pub struct PostHeader = "postFormat" {
18		/// 1.0, 2.0, 3.0 or 4.0.
19		pub format_type: f64 = "formatType" as F16Dot16,
20		/// Italic angle in degrees.
21		pub italic_angle: f64 = "italicAngle" as F16Dot16,
22		/// Underline position.
23		pub underline_position: i16 = "underlinePosition" as I16,
24		/// Underline thickness.
25		pub underline_thickness: i16 = "underlineThickness" as I16,
26		/// Non-zero for monospaced fonts.
27		pub is_fixed_pitch: u32 = "isFixedPitch" as U32,
28		/// Minimum memory if the font is downloaded as Type 42.
29		pub min_mem_type42: u32 = "minMemType42" as U32,
30		/// Maximum memory if the font is downloaded as Type 42.
31		pub max_mem_type42: u32 = "maxMemType42" as U32,
32		/// Minimum memory if the font is downloaded as Type 1.
33		pub min_mem_type1: u32 = "minMemType1" as U32,
34		/// Maximum memory if the font is downloaded as Type 1.
35		pub max_mem_type1: u32 = "maxMemType1" as U32,
36	}
37}
38
39/// PostScript table (`table__p_o_s_t`).
40///
41/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/post>.
42#[derive(Debug, Clone, PartialEq, Default)]
43pub struct Post {
44	/// The fixed fields.
45	pub header: PostHeader,
46	/// Glyph names that differ from the names in the `post` table, because those
47	/// were empty or not unique (`mapping`; formats 2 and 4).
48	pub mapping: Option<BTreeMap<String, String>>,
49	/// The names not in the standard Macintosh glyph order (`extraNames`; format
50	/// 2).
51	pub extra_names: Option<Vec<String>>,
52	/// Raw data from TTX `<hexdata>` (`data`). Never set when decompiling.
53	pub data: Option<Vec<u8>>,
54	/// The glyph order found while decompiling, until the font takes it.
55	/// `Some(None)` means the table has no glyph names (format 3).
56	glyph_order: Option<Option<Vec<String>>>,
57}
58
59impl std::ops::Deref for Post {
60	type Target = PostHeader;
61	fn deref(&self) -> &PostHeader {
62		&self.header
63	}
64}
65
66impl std::ops::DerefMut for Post {
67	fn deref_mut(&mut self) -> &mut PostHeader {
68		&mut self.header
69	}
70}
71
72impl Post {
73	/// Hands the glyph names found while decompiling to the font (`getGlyphOrder`).
74	/// Only [`Font::glyph_order`] should call this.
75	pub(crate) fn take_glyph_order(&mut self) -> Result<Option<Vec<String>>> {
76		self.glyph_order
77			.take()
78			.ok_or_else(|| Error::ttlib("illegal use of getGlyphOrder()"))
79	}
80
81	fn decode_format_2_0(&mut self, data: &[u8], glyph_count: usize) -> Result<()> {
82		let mut r = Reader::new(data);
83		let mut num_glyphs = r.u16()? as usize;
84		if num_glyphs > glyph_count {
85			// Assume the numGlyphs field is bogus, so sync with maxp.
86			num_glyphs = glyph_count;
87		}
88		// fontTools reads the indices with array.frombytes(), which rejects an odd
89		// number of bytes, and then fails with an IndexError if there are too few.
90		if r.remaining() < 2 * num_glyphs {
91			return Err(Error::ttlib(if r.remaining() % 2 == 1 {
92				"bytes length not a multiple of item size"
93			} else {
94				"array index out of range"
95			}));
96		}
97		let indices = r.u16_array(num_glyphs)?;
98		let string_data = data.get(2 + 2 * num_glyphs..).unwrap_or_default();
99		let max_index = indices.iter().copied().max().unwrap_or(0) as i64;
100		let extra_names = unpack_pstrings(string_data, (max_index - 257).max(0) as usize);
101		let mut glyph_order = vec![String::new(); glyph_count];
102		for (gid, &index) in indices.iter().enumerate() {
103			glyph_order[gid] = if index > 257 {
104				extra_names
105					.get(index as usize - 258)
106					.cloned()
107					.unwrap_or_default()
108			} else {
109				STANDARD_GLYPH_ORDER[index as usize].to_owned()
110			};
111		}
112		self.extra_names = Some(extra_names);
113		self.build_ps_name_mapping(glyph_order, glyph_count);
114		Ok(())
115	}
116
117	fn decode_format_4_0(&mut self, data: &[u8], glyph_count: usize) -> Result<()> {
118		if data.len() % 2 == 1 {
119			return Err(Error::value("bytes length not a multiple of item size"));
120		}
121		let indices: Vec<u16> = data
122			.as_chunks::<2>()
123			.0
124			.iter()
125			.map(|&c| u16::from_be_bytes(c))
126			.collect();
127		let mut glyph_order = vec![String::new(); glyph_count];
128		for (i, &index) in indices.iter().take(glyph_count).enumerate() {
129			glyph_order[i] = if index == 0xFFFF {
130				String::new()
131			} else if let Some(name) = fontoxide_misc::agl::uv2agl(index as u32) {
132				name.to_owned()
133			} else {
134				format!("uni{index:04X}")
135			};
136		}
137		self.build_ps_name_mapping(glyph_order, glyph_count);
138		Ok(())
139	}
140
141	/// Makes the names unique, recording the original names (`build_psNameMapping`).
142	fn build_ps_name_mapping(&mut self, mut glyph_order: Vec<String>, glyph_count: usize) {
143		let mut mapping = BTreeMap::new();
144		let mut all_names: HashMap<String, usize> = HashMap::new();
145		let glyph_order_names: HashSet<String> = glyph_order.iter().cloned().collect();
146		for (i, slot) in glyph_order.iter_mut().enumerate().take(glyph_count) {
147			let ps_name = slot.clone();
148			let mut glyph_name = if ps_name.is_empty() {
149				crate::glyph_order::synthesized_name(i as u32)
150			} else {
151				ps_name.clone()
152			};
153			if let Some(&count) = all_names.get(&glyph_name) {
154				// Make up a new glyph name that's unique.
155				let mut n = count;
156				while glyph_order_names.contains(&format!("{glyph_name}.{n}")) {
157					n += 1;
158				}
159				all_names.insert(glyph_name.clone(), n + 1);
160				glyph_name = format!("{glyph_name}.{n}");
161			}
162			all_names.insert(glyph_name.clone(), 1);
163			if glyph_name != ps_name {
164				*slot = glyph_name.clone();
165				mapping.insert(glyph_name, ps_name);
166			}
167		}
168		self.mapping = Some(mapping);
169		self.glyph_order = Some(Some(glyph_order));
170	}
171
172	fn encode_format_2_0(&mut self, font: &mut Font) -> Result<Vec<u8>> {
173		let num_glyphs = font.glyph_count()?;
174		let glyph_order = font.glyph_order()?;
175		if glyph_order.len() != num_glyphs {
176			return Err(Error::Assertion("len(glyphOrder) == numGlyphs".into()));
177		}
178		let standard: HashMap<&str, usize> = STANDARD_GLYPH_ORDER
179			.iter()
180			.enumerate()
181			.rev()
182			.map(|(i, n)| (*n, i))
183			.collect();
184		let mut extra_names: Vec<String> = self
185			.extra_names
186			.as_deref()
187			.ok_or_else(|| Error::ttlib("'post' table has no 'extraNames'"))?
188			.iter()
189			.filter(|n| !standard.contains_key(n.as_str()))
190			.cloned()
191			.collect();
192		let mut extra_dict: HashMap<String, usize> = HashMap::new();
193		for (i, name) in extra_names.iter().enumerate() {
194			extra_dict.insert(name.clone(), i);
195		}
196		let mapping = self
197			.mapping
198			.as_ref()
199			.ok_or_else(|| Error::ttlib("'post' table has no 'mapping'"))?;
200		let mut indices = Vec::with_capacity(num_glyphs);
201		for glyph_name in glyph_order.names() {
202			let ps_name = mapping.get(glyph_name).unwrap_or(glyph_name);
203			let index = if let Some(&i) = extra_dict.get(ps_name) {
204				258 + i
205			} else if let Some(&i) = standard.get(ps_name.as_str()) {
206				i
207			} else {
208				let i = extra_names.len();
209				extra_dict.insert(ps_name.clone(), i);
210				extra_names.push(ps_name.clone());
211				258 + i
212			};
213			indices.push(crate::binary::fit::<u16, _>(index, "glyphNameIndex")?);
214		}
215		let mut data = Vec::new();
216		data.put_u16(crate::binary::fit(num_glyphs, "numGlyphs")?);
217		for i in indices {
218			data.put_u16(i);
219		}
220		data.extend(pack_pstrings(&extra_names)?);
221		self.extra_names = Some(extra_names);
222		Ok(data)
223	}
224
225	fn encode_format_4_0(&self, font: &mut Font) -> Result<Vec<u8>> {
226		let num_glyphs = font.glyph_count()?;
227		let glyph_order = font.glyph_order()?;
228		if glyph_order.len() != num_glyphs {
229			return Err(Error::Assertion("len(glyphOrder) == numGlyphs".into()));
230		}
231		let mut data = Vec::with_capacity(2 * num_glyphs);
232		for name in glyph_order.names() {
233			let name = name.split('#').next().unwrap_or_default();
234			let index = if let Some(uv) = fontoxide_misc::agl::agl2uv(name) {
235				crate::binary::fit(uv, "index")?
236			} else if name.chars().count() == 7 && name.starts_with("uni") {
237				let hex = &name[3..];
238				let v = u32::from_str_radix(hex.trim(), 16).map_err(|_| {
239					Error::value(format!("invalid literal for int() with base 16: {hex:?}"))
240				})?;
241				crate::binary::fit(v, "index")?
242			} else {
243				0xFFFF
244			};
245			data.put_u16(index);
246		}
247		Ok(data)
248	}
249}
250
251/// Reads `n` Pascal strings; missing ones are empty (`unpackPStrings`).
252fn unpack_pstrings(data: &[u8], n: usize) -> Vec<String> {
253	let mut strings = Vec::with_capacity(n);
254	let mut index = 0usize;
255	let len = data.len();
256	for _ in 0..n {
257		let length = if len <= index {
258			0
259		} else {
260			data[index] as usize
261		};
262		index += 1;
263		let name = if (len as isize) < (index + length) as isize {
264			String::new()
265		} else {
266			fontoxide_misc::py::latin1_decode(&data[index..index + length])
267		};
268		strings.push(name);
269		index += length;
270	}
271	if index < len {
272		log::warn!("{} extra bytes in post.stringData array", len - index);
273	} else if len < index {
274		log::warn!("not enough data in post.stringData array");
275	}
276	strings
277}
278
279/// Packs strings as Pascal strings in Latin-1 (`packPStrings`).
280fn pack_pstrings(strings: &[String]) -> Result<Vec<u8>> {
281	let mut data = Vec::new();
282	for s in strings {
283		let bytes = fontoxide_misc::py::latin1_encode(s)
284			.ok_or_else(|| Error::value(format!("'latin-1' codec can't encode {s:?}")))?;
285		let len: u8 = u8::try_from(s.chars().count())
286			.map_err(|_| Error::value("bytes must be in range(0, 256)"))?;
287		data.push(len);
288		data.extend(bytes);
289	}
290	Ok(data)
291}
292
293impl TableType for Post {
294	const TAG: Tag = Tag::new(b"post");
295
296	fn decompile(data: &[u8], font: &mut Font) -> Result<Self> {
297		let header_data = &data[..data.len().min(PostHeader::SIZE)];
298		if header_data.len() != PostHeader::SIZE {
299			return Err(Error::Struct(format!(
300				"unpack requires a buffer of {} bytes",
301				PostHeader::SIZE
302			)));
303		}
304		let (header, rest) = PostHeader::unpack2(data)?;
305		let mut post = Post {
306			header,
307			..Default::default()
308		};
309		match post.format_type {
310			1.0 => {
311				let count = font.glyph_count()?;
312				post.glyph_order = Some(Some(
313					STANDARD_GLYPH_ORDER
314						.iter()
315						.take(count)
316						.map(|s| (*s).to_owned())
317						.collect(),
318				));
319			}
320			2.0 if font.skip_post_glyph_names => post.glyph_order = Some(None),
321			2.0 => {
322				let count = font.glyph_count()?;
323				post.decode_format_2_0(rest, count)?;
324			}
325			3.0 => post.glyph_order = Some(None),
326			4.0 => {
327				let count = font.glyph_count()?;
328				post.decode_format_4_0(rest, count)?;
329			}
330			f => {
331				return Err(Error::ttlib(format!(
332					"'post' table format {f:.6} not supported"
333				)));
334			}
335		}
336		Ok(post)
337	}
338}
339
340impl Table for Post {
341	/// Glyph names come from the glyph order when compiling.
342	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
343		let _ = f;
344		Ok(())
345	}
346
347	fn tag(&self) -> Tag {
348		Self::TAG
349	}
350
351	fn compile(&mut self, font: &mut Font) -> Result<Vec<u8>> {
352		let mut data = Vec::new();
353		self.header.pack(&mut data)?;
354		match self.format_type {
355			1.0 | 3.0 => {}
356			2.0 => data.extend(self.encode_format_2_0(font)?),
357			4.0 => data.extend(self.encode_format_4_0(font)?),
358			f => {
359				return Err(Error::ttlib(format!(
360					"'post' table format {f:.6} not supported"
361				)));
362			}
363		}
364		Ok(data)
365	}
366
367	fn clone_table(&self) -> Box<dyn Table> {
368		Box::new(self.clone())
369	}
370}
371
372impl TableXml for Post {
373	fn to_xml(&self, writer: &mut XmlWriter, _font: &mut Font) -> Result<()> {
374		for (name, value) in self.header.values() {
375			writer.simpletag(name, &[("value", &value)]);
376			writer.newline();
377		}
378		if let Some(mapping) = &self.mapping {
379			writer.begintag("psNames", &[]);
380			writer.newline();
381			writer.comment(
382				"This file uses unique glyph names based on the information\n\
383				 found in the 'post' table. Since these names might not be unique,\n\
384				 we have to invent artificial names in case of clashes. In order to\n\
385				 be able to retain the original information, we need a name to\n\
386				 ps name mapping for those cases where they differ. That's what\n\
387				 you see below.\n",
388			);
389			writer.newline();
390			for (name, ps_name) in mapping {
391				writer.simpletag("psName", &[("name", name), ("psName", ps_name)]);
392				writer.newline();
393			}
394			writer.endtag("psNames");
395			writer.newline();
396		}
397		if let Some(extra_names) = &self.extra_names {
398			writer.begintag("extraNames", &[]);
399			writer.newline();
400			writer.comment(
401				"following are the name that are not taken from the standard Mac glyph order",
402			);
403			writer.newline();
404			for name in extra_names {
405				writer.simpletag("psName", &[("name", name)]);
406				writer.newline();
407			}
408			writer.endtag("extraNames");
409			writer.newline();
410		}
411		if let Some(data) = &self.data {
412			writer.begintag("hexdata", &[]);
413			writer.newline();
414			writer.dumphex(data);
415			writer.endtag("hexdata");
416			writer.newline();
417		}
418		Ok(())
419	}
420
421	fn from_xml(&mut self, element: &Element, _font: &mut Font) -> Result<()> {
422		match element.name.as_str() {
423			"psNames" => {
424				let mut mapping = BTreeMap::new();
425				for e in element.elements().filter(|e| e.name == "psName") {
426					let name = e.attr("name").ok_or_else(|| Error::ttx("missing 'name'"))?;
427					let ps_name = e
428						.attr("psName")
429						.ok_or_else(|| Error::ttx("missing 'psName'"))?;
430					mapping.insert(name.to_owned(), ps_name.to_owned());
431				}
432				self.mapping = Some(mapping);
433			}
434			"extraNames" => {
435				let mut names = Vec::new();
436				for e in element.elements().filter(|e| e.name == "psName") {
437					names.push(
438						e.attr("name")
439							.ok_or_else(|| Error::ttx("missing 'name'"))?
440							.to_owned(),
441					);
442				}
443				self.extra_names = Some(names);
444			}
445			"hexdata" => self.data = Some(read_hex(element)?),
446			name => {
447				let value = element
448					.attr("value")
449					.ok_or_else(|| Error::ttx(format!("missing 'value' on <{name}>")))?;
450				if !self.header.set_literal(name, &eval(value)?)? {
451					return Err(Error::ttx(format!("unknown 'post' field: {name}")));
452				}
453			}
454		}
455		Ok(())
456	}
457}
458
459#[cfg(test)]
460mod tests {
461	use super::*;
462
463	#[test]
464	fn format_matches_upstream() {
465		crate::sstruct::tests::check(PostHeader::FORMAT_NAME, PostHeader::FIELDS);
466	}
467
468	#[test]
469	fn pstrings() {
470		assert_eq!(unpack_pstrings(b"\x01a\x02bc", 2), ["a", "bc"]);
471		assert_eq!(unpack_pstrings(b"\x05ab", 2), ["", ""]);
472		assert_eq!(
473			pack_pstrings(&["a".into(), "bc".into()]).ok(),
474			Some(b"\x01a\x02bc".to_vec())
475		);
476	}
477}