Skip to main content

fontoxide_ttlib/tables/
ebdt.rs

1//! `EBDT`, `CBDT` and `bdat`: bitmap data (`fontTools.ttLib.tables.E_B_D_T_`,
2//! `C_B_D_T_`, `_b_d_a_t`).
3
4use std::borrow::Cow;
5use std::collections::{BTreeSet, HashMap};
6use std::path::{Path, PathBuf};
7
8use fontoxide_misc::Tag;
9use fontoxide_misc::text_tools::{de_hex_str, hex_str};
10use fontoxide_misc::xml_reader::Element;
11use fontoxide_misc::xml_writer::XmlWriter;
12
13use crate::binary::{Reader, WriteBytes, fit};
14use crate::sstruct::{F16Dot16, I8, U16, Value, eval};
15use crate::table::{Table, TableType, TableXml, read_hex};
16use crate::tables::eblc::{
17	BigGlyphMetrics, BitmapLocator, SmallGlyphMetrics, clip, int_attr, literal, metrics_to_xml,
18	required_attr,
19};
20use crate::{Error, Font, Result};
21
22crate::sstruct! {
23	/// The header (`ebdtTableVersionFormat`).
24	pub struct EbdtHeader = "ebdtTableVersionFormat" {
25		/// The table version.
26		pub version: f64 = "version" as F16Dot16,
27	}
28}
29
30crate::sstruct! {
31	/// A component of a composite bitmap, as stored (`ebdtComponentFormat`).
32	pub struct EbdtComponentRecord = "ebdtComponentFormat" {
33		/// The glyph ID of the component.
34		pub glyph_code: u16 = "glyphCode" as U16,
35		/// Horizontal offset.
36		pub x_offset: i8 = "xOffset" as I8,
37		/// Vertical offset.
38		pub y_offset: i8 = "yOffset" as I8,
39	}
40}
41
42/// A component of a composite bitmap (`EbdtComponent`).
43#[derive(Debug, Clone, PartialEq, Eq, Default)]
44pub struct EbdtComponent {
45	/// The glyph ID of the component (`name`, a glyph name in fontTools).
46	pub glyph: u32,
47	/// Horizontal offset (`xOffset`).
48	pub x_offset: i8,
49	/// Vertical offset (`yOffset`).
50	pub y_offset: i8,
51}
52
53/// The metrics of a parsed bitmap glyph.
54#[derive(Debug, Clone, PartialEq, Default)]
55pub enum GlyphMetrics {
56	/// The format has no metrics, or a TTX document did not give them.
57	#[default]
58	None,
59	/// `SmallGlyphMetrics`.
60	Small(SmallGlyphMetrics),
61	/// `BigGlyphMetrics`.
62	Big(BigGlyphMetrics),
63}
64
65/// A bitmap glyph with its data parsed (`BitmapGlyph` after `decompile`).
66#[derive(Debug, Clone, PartialEq, Default)]
67pub struct ParsedBitmapGlyph {
68	/// The image format.
69	pub format: u16,
70	/// The metrics (`metrics`).
71	pub metrics: GlyphMetrics,
72	/// The image (`imageData`).
73	pub image_data: Option<Vec<u8>>,
74	/// The components, in formats 8 and 9 (`componentArray`).
75	pub components: Option<Vec<EbdtComponent>>,
76}
77
78/// A bitmap glyph (`BitmapGlyph` and its subclasses).
79#[derive(Debug, Clone, PartialEq)]
80pub enum BitmapGlyph {
81	/// The data as read, parsed only when the glyph is used.
82	///
83	/// As in fontTools, malformed data only fails if the glyph is used.
84	///
85	/// The components of formats 8 and 9 are only resolved then too, with the
86	/// glyph order of that time: [`Table::remap_glyphs`] leaves this data alone,
87	/// so that the glyph IDs stay as they are. To remap them, parse the glyph
88	/// first ([`BitmapGlyph::ensure_decompiled`]), as the subsetter does.
89	Raw {
90		/// The image format.
91		format: u16,
92		/// The data.
93		data: Vec<u8>,
94	},
95	/// The parsed glyph; read from TTX.
96	Parsed(ParsedBitmapGlyph),
97}
98
99fn missing(attribute: &str) -> Error {
100	Error::ttlib(format!("AttributeError: {attribute}"))
101}
102
103/// The error of `sstruct.getformat(ebdtComponentFormat)[1][1:]`.
104fn component_format_error() -> Error {
105	Error::ttlib("KeyError: slice(1, None, None)")
106}
107
108/// Whether a format is one of `ebdt_bitmap_classes`.
109fn is_ebdt_format(format: u16) -> bool {
110	matches!(format, 1 | 2 | 5..=9)
111}
112
113/// Whether a format is one of `cbdt_bitmap_classes`.
114fn is_cbdt_format(format: u16) -> bool {
115	matches!(format, 17..=19)
116}
117
118fn check_format<const COLOR: bool>(format: u16) -> Result<()> {
119	if is_ebdt_format(format) || (COLOR && is_cbdt_format(format)) {
120		Ok(())
121	} else {
122		Err(Error::ttlib(format!("KeyError: {format}")))
123	}
124}
125
126/// Formats that use `BitAlignedBitmapMixin`.
127fn is_bit_aligned(format: u16) -> bool {
128	matches!(format, 2 | 5 | 7)
129}
130
131/// Formats that use `ByteAlignedBitmapMixin`.
132fn is_byte_aligned(format: u16) -> bool {
133	matches!(format, 1 | 6)
134}
135
136fn read_components(mut data: &[u8]) -> Result<Vec<EbdtComponent>> {
137	let mut r = Reader::new(data);
138	let count = r.u16()?;
139	data = r.rest();
140	let mut components = Vec::new();
141	for _ in 0..count {
142		let (c, rest) = EbdtComponentRecord::unpack2(data)?;
143		data = rest;
144		components.push(EbdtComponent {
145			glyph: u32::from(c.glyph_code),
146			x_offset: c.x_offset,
147			y_offset: c.y_offset,
148		});
149	}
150	Ok(components)
151}
152
153/// The length-prefixed image of formats 17 to 19.
154fn read_prefixed(data: &[u8], format: u16) -> Result<Vec<u8>> {
155	let mut r = Reader::new(data);
156	let len = r.u32()? as usize;
157	let rest = r.rest();
158	if len > rest.len() {
159		return Err(Error::Assertion(format!("Data overun in format {format}")));
160	}
161	Ok(rest[..len].to_vec())
162}
163
164impl ParsedBitmapGlyph {
165	/// Parses the data of a glyph in an image format (`decompile`).
166	pub fn parse(format: u16, data: &[u8]) -> Result<Self> {
167		let mut glyph = ParsedBitmapGlyph {
168			format,
169			..Default::default()
170		};
171		match format {
172			1 | 2 => {
173				let (metrics, rest) = SmallGlyphMetrics::unpack2(data)?;
174				glyph.metrics = GlyphMetrics::Small(metrics);
175				glyph.image_data = Some(rest.to_vec());
176			}
177			5 => glyph.image_data = Some(data.to_vec()),
178			6 | 7 => {
179				let (metrics, rest) = BigGlyphMetrics::unpack2(data)?;
180				glyph.metrics = GlyphMetrics::Big(metrics);
181				glyph.image_data = Some(rest.to_vec());
182			}
183			8 => {
184				let (metrics, rest) = SmallGlyphMetrics::unpack2(data)?;
185				glyph.metrics = GlyphMetrics::Small(metrics);
186				glyph.components = Some(read_components(rest.get(1..).unwrap_or_default())?);
187			}
188			9 => {
189				let (metrics, rest) = BigGlyphMetrics::unpack2(data)?;
190				glyph.metrics = GlyphMetrics::Big(metrics);
191				glyph.components = Some(read_components(rest)?);
192			}
193			17 => {
194				let (metrics, rest) = SmallGlyphMetrics::unpack2(data)?;
195				glyph.metrics = GlyphMetrics::Small(metrics);
196				glyph.image_data = Some(read_prefixed(rest, format)?);
197			}
198			18 => {
199				let (metrics, rest) = BigGlyphMetrics::unpack2(data)?;
200				glyph.metrics = GlyphMetrics::Big(metrics);
201				glyph.image_data = Some(read_prefixed(rest, format)?);
202			}
203			19 => glyph.image_data = Some(read_prefixed(data, format)?),
204			f => return Err(Error::ttlib(format!("KeyError: {f}"))),
205		}
206		Ok(glyph)
207	}
208
209	fn pack_metrics(&self, out: &mut Vec<u8>) -> Result<()> {
210		match (&self.metrics, self.format) {
211			(GlyphMetrics::Small(m), 1 | 2 | 8 | 17) => m.pack(out),
212			(GlyphMetrics::Big(m), 6 | 7 | 9 | 18) => m.pack(out),
213			(_, 5 | 19) => Ok(()),
214			_ => Err(missing("metrics")),
215		}
216	}
217
218	fn image(&self) -> Result<&[u8]> {
219		self.image_data
220			.as_deref()
221			.ok_or_else(|| missing("imageData"))
222	}
223
224	/// The data of the glyph (`compile`).
225	pub fn compile(&self) -> Result<Vec<u8>> {
226		let mut out = Vec::new();
227		self.pack_metrics(&mut out)?;
228		match self.format {
229			1 | 2 | 5 | 6 | 7 => out.extend_from_slice(self.image()?),
230			8 | 9 => {
231				if self.format == 8 {
232					out.put_u8(0);
233				}
234				let components = self
235					.components
236					.as_ref()
237					.ok_or_else(|| missing("componentArray"))?;
238				out.put_u16(fit(components.len(), "numComponents")?);
239				for c in components {
240					EbdtComponentRecord {
241						glyph_code: fit(c.glyph, "glyphCode")?,
242						x_offset: c.x_offset,
243						y_offset: c.y_offset,
244					}
245					.pack(&mut out)?;
246				}
247			}
248			17..=19 => {
249				let image = self.image()?;
250				out.put_u32(fit(image.len(), "dataLen")?);
251				out.extend_from_slice(image);
252			}
253			f => return Err(Error::ttlib(format!("KeyError: {f}"))),
254		}
255		Ok(out)
256	}
257
258	/// The width and height, if the glyph has metrics.
259	fn size(&self) -> Option<(usize, usize)> {
260		match &self.metrics {
261			GlyphMetrics::None => None,
262			GlyphMetrics::Small(m) => Some((usize::from(m.width), usize::from(m.height))),
263			GlyphMetrics::Big(m) => Some((usize::from(m.width), usize::from(m.height))),
264		}
265	}
266
267	/// `getRow` of `BitAlignedBitmapMixin` and `ByteAlignedBitmapMixin`.
268	fn row(&self, row: usize, bit_depth: usize, width: usize, reverse: bool) -> Result<Vec<u8>> {
269		let image = self.image()?;
270		if is_byte_aligned(self.format) {
271			let row_bytes = (bit_depth * width).div_ceil(8);
272			let start = (row * row_bytes) as u64;
273			let data = clip(image, start, start + row_bytes as u64);
274			return Ok(if reverse {
275				reverse_bytes(data)
276			} else {
277				data.to_vec()
278			});
279		}
280		if !is_bit_aligned(self.format) {
281			return Err(missing("getRow"));
282		}
283		let row_bits = bit_depth * width;
284		let start = row * row_bits;
285		let end = start + row_bits;
286		let mut out = Vec::with_capacity(row_bits.div_ceil(8));
287		for cur_bit in (start..end).step_by(8) {
288			let end_bit = (cur_bit + 8).min(end);
289			let num_bits = end_bit - cur_bit;
290			let cut_point = cur_bit % 8;
291			let first = cur_bit / 8;
292			let second = end_bit / 8;
293			let num_bits_cut = if first < second {
294				8 - cut_point
295			} else {
296				end_bit - cur_bit
297			};
298			let byte = image
299				.get(first)
300				.ok_or_else(|| Error::ttlib("IndexError: index out of range"))?
301				.reverse_bits();
302			let first_half = (u32::from(byte) >> cut_point) & ((1 << num_bits_cut) - 1);
303			let mut new_byte = first_half;
304			if first < second
305				&& let Some(next) = image.get(second)
306			{
307				let second_half = u32::from(next.reverse_bits()) << num_bits_cut;
308				new_byte = (first_half | second_half) & ((1 << num_bits) - 1);
309			}
310			out.push(new_byte as u8);
311		}
312		Ok(if reverse { out } else { reverse_bytes(&out) })
313	}
314
315	/// `setRows` of `BitAlignedBitmapMixin` and `ByteAlignedBitmapMixin`.
316	fn set_rows(
317		&mut self,
318		rows: Vec<Vec<u8>>,
319		bit_depth: usize,
320		width: usize,
321		reverse: bool,
322	) -> Result<()> {
323		if is_byte_aligned(self.format) {
324			let image = rows
325				.iter()
326				.flat_map(|row| {
327					if reverse {
328						reverse_bytes(row)
329					} else {
330						row.clone()
331					}
332				})
333				.collect();
334			self.image_data = Some(image);
335			return Ok(());
336		}
337		if !is_bit_aligned(self.format) {
338			return Err(missing("setRows"));
339		}
340		let row_bits = bit_depth * width;
341		let num_bytes = (rows.len() * row_bits).div_ceil(8);
342		let mut image = vec![0u8; num_bytes];
343		for (row, data) in rows.iter().enumerate() {
344			let start = row * row_bits;
345			let end = start + row_bits;
346			for (cur_bit, &byte) in (start..end).step_by(8).zip(data) {
347				let byte = if reverse { byte } else { byte.reverse_bits() };
348				let end_bit = (cur_bit + 8).min(end);
349				let cut_point = cur_bit % 8;
350				let first = cur_bit / 8;
351				let second = end_bit / 8;
352				let num_bits_cut = if first < second {
353					8 - cut_point
354				} else {
355					end_bit - cur_bit
356				};
357				let first_byte = u32::from(byte) & ((1 << num_bits_cut) - 1);
358				image[first] |= (first_byte << cut_point) as u8;
359				if first < second && second < num_bytes {
360					let second_byte =
361						(u32::from(byte) >> num_bits_cut) & ((1 << (8 - num_bits_cut)) - 1);
362					image[second] |= second_byte as u8;
363				}
364			}
365		}
366		self.image_data = Some(reverse_bytes(&image));
367		Ok(())
368	}
369
370	fn metrics_to_xml(&self, writer: &mut XmlWriter) {
371		match &self.metrics {
372			GlyphMetrics::None => {}
373			GlyphMetrics::Small(m) => metrics_to_xml(writer, "SmallGlyphMetrics", m.values()),
374			GlyphMetrics::Big(m) => metrics_to_xml(writer, "BigGlyphMetrics", m.values()),
375		}
376	}
377
378	fn from_xml(format: u16, element: &Element) -> Result<Self> {
379		let mut glyph = ParsedBitmapGlyph {
380			format,
381			..Default::default()
382		};
383		let small = matches!(format, 1 | 2 | 8 | 17);
384		let big = matches!(format, 6 | 7 | 9 | 18);
385		for child in element.elements() {
386			match child.name.as_str() {
387				"SmallGlyphMetrics" if small => {
388					let mut metrics = SmallGlyphMetrics::default();
389					for m in child.elements() {
390						if !metrics.set_literal(&m.name, &literal(m)?)? {
391							log::warn!(
392								"unknown name '{}' being ignored in SmallGlyphMetrics.",
393								m.name
394							);
395						}
396					}
397					glyph.metrics = GlyphMetrics::Small(metrics);
398				}
399				"BigGlyphMetrics" if big => {
400					let mut metrics = BigGlyphMetrics::default();
401					for m in child.elements() {
402						if !metrics.set_literal(&m.name, &literal(m)?)? {
403							log::warn!(
404								"unknown name '{}' being ignored in BigGlyphMetrics.",
405								m.name
406							);
407						}
408					}
409					glyph.metrics = GlyphMetrics::Big(metrics);
410				}
411				"SmallGlyphMetrics" | "BigGlyphMetrics" if small || big => {
412					log::warn!("Warning: {} being ignored in format {format}.", child.name);
413				}
414				_ => {}
415			}
416		}
417		if matches!(format, 8 | 9) {
418			for child in element.elements() {
419				if child.name != "components" {
420					continue;
421				}
422				for c in child.elements() {
423					if c.name != "ebdtComponent" {
424						log::warn!("'{}' being ignored in component array.", c.name);
425						continue;
426					}
427					// UPSTREAM-BUG(B21): `EbdtComponent.fromXML` slices a dict, so a
428					// composite with components cannot be read.
429					return Err(component_format_error());
430				}
431				glyph.components = Some(Vec::new());
432			}
433			return Ok(glyph);
434		}
435		for child in element.elements() {
436			let Some(option) = child.name.strip_suffix("imagedata") else {
437				continue;
438			};
439			match option {
440				"raw" => glyph.image_data = Some(read_hex(child)?),
441				"row" if !is_cbdt_format(format) => glyph.read_rows(child)?,
442				"bitwise" => glyph.read_bitwise(child)?,
443				"extfile" => {
444					glyph.image_data = Some(std::fs::read(required_attr(child, "value")?)?);
445				}
446				_ => {
447					return Err(Error::Assertion(format!(
448						"unknown image data option: {option}"
449					)));
450				}
451			}
452		}
453		Ok(glyph)
454	}
455
456	/// `_readRowImageData`.
457	fn read_rows(&mut self, element: &Element) -> Result<()> {
458		let bit_depth: usize = int_attr(element, "bitDepth")?;
459		let width: usize = int_attr(element, "width")?;
460		let _: i64 = int_attr(element, "height")?;
461		let mut rows = Vec::new();
462		for child in element.elements() {
463			if child.name == "row" {
464				let value = required_attr(child, "value")?;
465				rows.push(de_hex_str(value).ok_or_else(|| Error::value("invalid hex data"))?);
466			}
467		}
468		self.set_rows(rows, bit_depth, width, false)
469	}
470
471	/// `_readBitwiseImageData`.
472	fn read_bitwise(&mut self, element: &Element) -> Result<()> {
473		let bit_depth: usize = int_attr(element, "bitDepth")?;
474		let width: usize = int_attr(element, "width")?;
475		let _: i64 = int_attr(element, "height")?;
476		let mut rows = Vec::new();
477		for child in element.elements() {
478			if child.name == "row" {
479				let bits: Vec<bool> = required_attr(child, "value")?
480					.chars()
481					.map(|c| !matches!(c, ' ' | '.' | '0'))
482					.collect();
483				// `_binary2data`.
484				let row = bits
485					.chunks(8)
486					.map(|chunk| {
487						chunk
488							.iter()
489							.rev()
490							.fold(0u8, |byte, &bit| (byte << 1) | u8::from(bit))
491					})
492					.collect();
493				rows.push(row);
494			}
495		}
496		self.set_rows(rows, bit_depth, width, true)
497	}
498}
499
500/// `_reverseBytes`: reverses the bits of each byte.
501fn reverse_bytes(data: &[u8]) -> Vec<u8> {
502	data.iter().map(|b| b.reverse_bits()).collect()
503}
504
505/// `_extFileName`: the file name for a glyph name, which may come straight from
506/// the font and contain path separators.
507fn ext_file_name(glyph_name: &str) -> String {
508	if !matches!(glyph_name, "" | "." | "..") && !glyph_name.contains(['%', '/', '\\']) {
509		return glyph_name.to_owned();
510	}
511	let mut out = String::from("%");
512	for &b in glyph_name.as_bytes() {
513		if b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-' | b'~') {
514			out.push(b as char);
515		} else {
516			out.push_str(&format!("%{b:02X}"));
517		}
518	}
519	out
520}
521
522/// The glyphs of a strike (the dictionaries of `strikeData`): glyph IDs in order
523/// of insertion, and the glyph of each in [`BitmapData::glyphs`].
524#[derive(Debug, Clone, PartialEq, Default)]
525pub struct StrikeData {
526	order: Vec<u32>,
527	glyphs: HashMap<u32, usize>,
528}
529
530impl StrikeData {
531	/// Adds a glyph, by its index in [`BitmapData::glyphs`]; a glyph that is
532	/// already there keeps its place.
533	pub fn insert(&mut self, gid: u32, index: usize) {
534		if self.glyphs.insert(gid, index).is_none() {
535			self.order.push(gid);
536		}
537	}
538
539	/// The glyph IDs of the strike, in order.
540	pub fn glyph_ids(&self) -> &[u32] {
541		&self.order
542	}
543
544	/// The index in [`BitmapData::glyphs`] of a glyph of the strike.
545	pub fn get(&self, gid: u32) -> Option<usize> {
546		self.glyphs.get(&gid).copied()
547	}
548
549	/// Whether the strike has no glyphs.
550	pub fn is_empty(&self) -> bool {
551		self.order.is_empty()
552	}
553
554	/// Keeps only the given glyphs.
555	pub fn retain(&mut self, glyphs: &BTreeSet<u32>) {
556		self.order.retain(|g| glyphs.contains(g));
557		self.glyphs.retain(|g, _| glyphs.contains(g));
558	}
559}
560
561/// The size and bit depth used to dump a glyph (`exportMetrics`, `exportBitDepth`).
562#[derive(Clone, Copy)]
563struct Export {
564	width: usize,
565	height: usize,
566	bit_depth: usize,
567}
568
569/// Embedded (`COLOR` false) or Color (`COLOR` true) Bitmap Data table
570/// (`table_E_B_D_T_`, `table_C_B_D_T_`), or with `APPLE`, Apple's `bdat`
571/// (`table__b_d_a_t`).
572///
573/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/ebdt> and
574/// <https://learn.microsoft.com/en-us/typography/opentype/spec/cbdt>.
575#[derive(Debug, Clone, PartialEq, Default)]
576pub struct BitmapData<const COLOR: bool, const APPLE: bool = false> {
577	/// The table version.
578	pub version: f64,
579	/// All glyphs. Strikes refer to them by index, so that glyphs at the same
580	/// location share an entry (object identity in fontTools).
581	pub glyphs: Vec<BitmapGlyph>,
582	/// The glyphs by strike (`strikeData`). Only a TTX document with gaps in its
583	/// strike indices leaves `None`s.
584	pub strike_data: Vec<Option<StrikeData>>,
585}
586
587/// `EBDT`.
588pub type Ebdt = BitmapData<false>;
589/// `CBDT`.
590pub type Cbdt = BitmapData<true>;
591/// `bdat`: Apple's `EBDT` (`table__b_d_a_t`), with `bloc`.
592pub type Bdat = BitmapData<false, true>;
593
594impl BitmapGlyph {
595	/// The glyph with its data parsed, which fails on malformed data.
596	pub fn parsed(&self) -> Result<Cow<'_, ParsedBitmapGlyph>> {
597		match self {
598			BitmapGlyph::Raw { format, data } => {
599				Ok(Cow::Owned(ParsedBitmapGlyph::parse(*format, data)?))
600			}
601			BitmapGlyph::Parsed(p) => Ok(Cow::Borrowed(p)),
602		}
603	}
604
605	/// The image format.
606	pub fn format(&self) -> u16 {
607		match self {
608			BitmapGlyph::Raw { format, .. } => *format,
609			BitmapGlyph::Parsed(p) => p.format,
610		}
611	}
612
613	/// Whether the glyph is a composite (`ComponentBitmapGlyph`: formats 8 and 9).
614	pub fn is_composite(&self) -> bool {
615		matches!(self.format(), 8 | 9)
616	}
617
618	/// `ensureDecompiled`: parses the data in place, which fails on malformed
619	/// data.
620	pub fn ensure_decompiled(&mut self) -> Result<()> {
621		if let BitmapGlyph::Raw { format, data } = self {
622			*self = BitmapGlyph::Parsed(ParsedBitmapGlyph::parse(*format, data)?);
623		}
624		Ok(())
625	}
626}
627
628impl<const COLOR: bool, const APPLE: bool> TableType for BitmapData<COLOR, APPLE> {
629	const TAG: Tag = if COLOR {
630		Tag::new(b"CBDT")
631	} else if APPLE {
632		Tag::new(b"bdat")
633	} else {
634		Tag::new(b"EBDT")
635	};
636
637	fn decompile(data: &[u8], font: &mut Font) -> Result<Self> {
638		let (header, _) = EbdtHeader::unpack2(data)?;
639		let locator = font.require::<BitmapLocator<COLOR, APPLE>>()?;
640		let mut seen: HashMap<(u64, u64), usize> = HashMap::new();
641		let mut glyphs = Vec::new();
642		let mut strike_data = Vec::with_capacity(locator.strikes.len());
643		for strike in locator.strikes.iter().flatten() {
644			let mut dict = StrikeData::default();
645			for table in &strike.index_sub_tables {
646				for (&gid, &location) in table.names.iter().zip(&table.locations) {
647					let index = match seen.get(&location) {
648						Some(&i) => i,
649						None => {
650							check_format::<COLOR>(table.image_format)?;
651							glyphs.push(BitmapGlyph::Raw {
652								format: table.image_format,
653								data: clip(data, location.0, location.1).to_vec(),
654							});
655							seen.insert(location, glyphs.len() - 1);
656							glyphs.len() - 1
657						}
658					};
659					dict.insert(gid, index);
660				}
661			}
662			strike_data.push(Some(dict));
663		}
664		Ok(BitmapData {
665			version: header.version,
666			glyphs,
667			strike_data,
668		})
669	}
670}
671
672impl<const COLOR: bool, const APPLE: bool> BitmapData<COLOR, APPLE> {
673	/// `writeData` for a glyph with image data.
674	fn write_image(
675		&self,
676		writer: &mut XmlWriter,
677		font: &Font,
678		parsed: &ParsedBitmapGlyph,
679		export: Option<Export>,
680		strike_index: usize,
681		glyph_name: &str,
682	) -> Result<()> {
683		let is_color = is_cbdt_format(parsed.format);
684		match font.bitmap_glyph_data_format.as_str() {
685			"row" if !is_color => {
686				let e = export.ok_or_else(|| missing("exportMetrics"))?;
687				writer.begintag(
688					"rowimagedata",
689					&[
690						("bitDepth", &e.bit_depth),
691						("width", &e.width),
692						("height", &e.height),
693					],
694				);
695				writer.newline();
696				for row in 0..e.height {
697					let data = parsed.row(row, e.bit_depth, e.width, false)?;
698					writer.simpletag("row", &[("value", &hex_str(&data))]);
699					writer.newline();
700				}
701				writer.endtag("rowimagedata");
702				writer.newline();
703			}
704			"bitwise" => {
705				let e = export.ok_or_else(|| missing("exportMetrics"))?;
706				writer.begintag(
707					"bitwiseimagedata",
708					&[
709						("bitDepth", &e.bit_depth),
710						("width", &e.width),
711						("height", &e.height),
712					],
713				);
714				writer.newline();
715				for row in 0..e.height {
716					let data = parsed.row(row, 1, e.width, true)?;
717					// `_data2binary`.
718					let mut bits = String::with_capacity(e.width);
719					let mut num_bits = e.width;
720					for byte in data {
721						for i in 0..num_bits.min(8) {
722							bits.push(if byte >> i & 1 != 0 { '@' } else { '.' });
723						}
724						num_bits -= num_bits.min(8);
725					}
726					writer.simpletag("row", &[("value", &bits)]);
727					writer.newline();
728				}
729				writer.endtag("bitwiseimagedata");
730				writer.newline();
731			}
732			"extfile" => {
733				// LENIENT(L23): a dump is a string here, so that the files go where
734				// fontTools puts them if the output has no file name.
735				let extension = if is_color { ".png" } else { ".bin" };
736				let folder = Path::new(".")
737					.join("bitmaps")
738					.join(format!("strike{strike_index}"));
739				std::fs::create_dir_all(&folder)?;
740				let path: PathBuf =
741					folder.join(format!("{}{extension}", ext_file_name(glyph_name)));
742				writer.simpletag(
743					"extfileimagedata",
744					&[("value", &path.to_string_lossy().into_owned())],
745				);
746				writer.newline();
747				std::fs::write(&path, parsed.image()?)?;
748			}
749			_ => {
750				writer.begintag("rawimagedata", &[]);
751				writer.newline();
752				writer.dumphex(parsed.image()?);
753				writer.endtag("rawimagedata");
754				writer.newline();
755			}
756		}
757		Ok(())
758	}
759
760	/// The sizes and bit depths for the `row` and `bitwise` formats.
761	fn exports(&self, font: &mut Font) -> Result<HashMap<usize, Export>> {
762		let mut exports = HashMap::new();
763		let locator = font.require::<BitmapLocator<COLOR, APPLE>>()?;
764		for (strike, dict) in locator.strikes.iter().zip(&self.strike_data) {
765			let strike = strike.as_ref().ok_or_else(|| missing("indexSubTables"))?;
766			let dict = dict.as_ref().ok_or_else(|| missing("strikeData"))?;
767			let bit_depth = usize::from(strike.bitmap_size_table.part2.bit_depth);
768			for table in &strike.index_sub_tables {
769				for name in &table.names {
770					let index = *dict
771						.glyphs
772						.get(name)
773						.ok_or_else(|| Error::ttlib(format!("KeyError: glyph {name}")))?;
774					let parsed = self.glyphs[index].parsed()?;
775					let (width, height) = match parsed.size() {
776						Some(size) => size,
777						None => {
778							let m = table.metrics.as_ref().ok_or_else(|| missing("metrics"))?;
779							(usize::from(m.width), usize::from(m.height))
780						}
781					};
782					exports.insert(
783						index,
784						Export {
785							width,
786							height,
787							bit_depth,
788						},
789					);
790				}
791			}
792		}
793		Ok(exports)
794	}
795}
796
797impl<const COLOR: bool, const APPLE: bool> Table for BitmapData<COLOR, APPLE> {
798	fn tag(&self) -> Tag {
799		Self::TAG
800	}
801
802	fn compile(&mut self, font: &mut Font) -> Result<Vec<u8>> {
803		let mut out = Vec::new();
804		EbdtHeader {
805			version: self.version,
806		}
807		.pack(&mut out)?;
808		// Glyphs that have been written, by entry in `glyphs`.
809		let mut placed: HashMap<usize, (u64, u64)> = HashMap::new();
810		let locator = font.require::<BitmapLocator<COLOR, APPLE>>()?;
811		for (strike, dict) in locator.strikes.iter_mut().zip(&self.strike_data) {
812			let strike = strike.as_mut().ok_or_else(|| missing("indexSubTables"))?;
813			for table in &mut strike.index_sub_tables {
814				let mut locations = Vec::with_capacity(table.names.len());
815				for name in &table.names {
816					let dict = dict.as_ref().ok_or_else(|| missing("strikeData"))?;
817					let index = *dict
818						.glyphs
819						.get(name)
820						.ok_or_else(|| Error::ttlib(format!("KeyError: glyph {name}")))?;
821					let location = match placed.get(&index) {
822						Some(&location) => location,
823						None => {
824							let data = self.glyphs[index].parsed()?.compile()?;
825							let data = table.pad_bitmap_data(data)?;
826							let start = out.len() as u64;
827							out.extend_from_slice(&data);
828							let location = (start, out.len() as u64);
829							placed.insert(index, location);
830							location
831						}
832					};
833					locations.push(location);
834				}
835				table.locations = locations;
836			}
837		}
838		Ok(out)
839	}
840
841	fn clone_table(&self) -> Box<dyn Table> {
842		Box::new(self.clone())
843	}
844
845	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
846		let mut used = BTreeSet::new();
847		for dict in self.strike_data.iter_mut().flatten() {
848			let mut glyphs = HashMap::with_capacity(dict.glyphs.len());
849			for gid in &mut dict.order {
850				let index = dict.glyphs[gid];
851				used.insert(index);
852				*gid = f(*gid)?;
853				glyphs.insert(*gid, index);
854			}
855			dict.glyphs = glyphs;
856		}
857		for index in used {
858			if let BitmapGlyph::Parsed(parsed) = &mut self.glyphs[index] {
859				for c in parsed.components.iter_mut().flatten() {
860					c.glyph = f(c.glyph)?;
861				}
862			}
863		}
864		Ok(())
865	}
866}
867
868impl<const COLOR: bool, const APPLE: bool> TableXml for BitmapData<COLOR, APPLE> {
869	fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font) -> Result<()> {
870		let mut exports = if matches!(font.bitmap_glyph_data_format.as_str(), "row" | "bitwise") {
871			self.exports(font)?
872		} else {
873			font.require::<BitmapLocator<COLOR, APPLE>>()?;
874			HashMap::new()
875		};
876		writer.simpletag_ordered("header", &[("version", &Value::Float(self.version))]);
877		writer.newline();
878		let order = font.glyph_order()?;
879		for (strike_index, dict) in self.strike_data.iter().enumerate() {
880			let dict = dict.as_ref().ok_or_else(|| missing("strikeData"))?;
881			writer.begintag_ordered("strikedata", &[("index", &strike_index)]);
882			writer.newline();
883			for gid in dict.glyph_ids() {
884				let index = dict.glyphs[gid];
885				let parsed = self.glyphs[index].parsed()?;
886				let tag = if is_cbdt_format(parsed.format) {
887					format!("cbdt_bitmap_format_{}", parsed.format)
888				} else {
889					format!("ebdt_bitmap_format_{}", parsed.format)
890				};
891				let name = order.name(*gid);
892				writer.begintag_ordered(&tag, &[("name", &name)]);
893				writer.newline();
894				parsed.metrics_to_xml(writer);
895				if let Some(components) = &parsed.components {
896					writer.begintag("components", &[]);
897					writer.newline();
898					// UPSTREAM-BUG(B21): `EbdtComponent.toXML` slices a dict, so a
899					// composite with components cannot be dumped.
900					if !components.is_empty() {
901						return Err(component_format_error());
902					}
903					writer.endtag("components");
904					writer.newline();
905				} else {
906					// The export values are deleted once they are used.
907					let export = exports.remove(&index);
908					self.write_image(writer, font, &parsed, export, strike_index, &name)?;
909				}
910				writer.endtag(&tag);
911				writer.newline();
912			}
913			writer.endtag("strikedata");
914			writer.newline();
915		}
916		Ok(())
917	}
918
919	fn from_xml(&mut self, element: &Element, font: &mut Font) -> Result<()> {
920		match element.name.as_str() {
921			"header" => {
922				self.version = eval(required_attr(element, "version")?)?
923					.as_float()
924					.ok_or_else(|| Error::value("invalid value for version"))?;
925			}
926			"strikedata" => {
927				let strike_index: usize = int_attr(element, "index")?;
928				let mut dict = StrikeData::default();
929				for child in element.elements() {
930					let name = child.name.as_str();
931					if !name
932						.get(4..)
933						.is_some_and(|n| n.starts_with("_bitmap_format_"))
934					{
935						log::warn!("{name} being ignored by {}", Self::TAG);
936						continue;
937					}
938					let format = eval(&name[19..])?
939						.as_int()
940						.ok_or_else(|| Error::value("invalid image format"))?;
941					let format: u16 = fit(format, "imageFormat")?;
942					check_format::<COLOR>(format)?;
943					let glyph_name = required_attr(child, "name")?;
944					let glyph = ParsedBitmapGlyph::from_xml(format, child)?;
945					let gid = font.glyph_id(glyph_name)?;
946					if dict.glyphs.contains_key(&gid) {
947						return Err(Error::Assertion(format!(
948							"Duplicate glyphs with the same name '{glyph_name}' in the same strike."
949						)));
950					}
951					self.glyphs.push(BitmapGlyph::Parsed(glyph));
952					dict.insert(gid, self.glyphs.len() - 1);
953				}
954				if strike_index >= self.strike_data.len() {
955					self.strike_data.resize(strike_index + 1, None);
956				}
957				if self.strike_data[strike_index].is_some() {
958					return Err(Error::Assertion("Duplicate strike EBDT indices.".into()));
959				}
960				self.strike_data[strike_index] = Some(dict);
961			}
962			_ => {}
963		}
964		Ok(())
965	}
966}
967
968#[cfg(test)]
969mod tests {
970	use super::*;
971
972	#[test]
973	fn formats_match_upstream() {
974		use crate::sstruct::tests::check;
975		check(EbdtHeader::FORMAT_NAME, EbdtHeader::FIELDS);
976		check(
977			EbdtComponentRecord::FORMAT_NAME,
978			EbdtComponentRecord::FIELDS,
979		);
980	}
981
982	/// `test_lazy_bitmap_metrics_and_edited_metrics_are_preserved`, without the
983	/// edit.
984	#[test]
985	fn glyphs_compile_to_their_data() -> Result<()> {
986		let small = [1, 8, 0xFF, 1, 9];
987		let big = [1, 8, 0xFF, 1, 9, 0xFC, 2, 10];
988		let component = [0, 1, 0, 1, 0xFE, 3];
989		let prefixed = [0, 0, 0, 1, 0x81];
990		let cases: [(u16, Vec<u8>); 8] = [
991			(1, [&small[..], &[0x81]].concat()),
992			(2, [&small[..], &[0x81]].concat()),
993			(6, [&big[..], &[0x81]].concat()),
994			(7, [&big[..], &[0x81]].concat()),
995			(8, [&small[..], &[0], &component[..]].concat()),
996			(9, [&big[..], &component[..]].concat()),
997			(17, [&small[..], &prefixed[..]].concat()),
998			(18, [&big[..], &prefixed[..]].concat()),
999		];
1000		for (format, data) in cases {
1001			let glyph = ParsedBitmapGlyph::parse(format, &data)?;
1002			assert_eq!(glyph.compile()?, data, "format {format}");
1003		}
1004		Ok(())
1005	}
1006
1007	/// Glyphs left as read keep their component IDs; parsed glyphs are remapped.
1008	#[test]
1009	fn remap_leaves_raw_components() -> Result<()> {
1010		let data = [&[1, 8, 0xFF, 1, 9, 0, 0, 1, 0, 5, 1, 2][..]].concat();
1011		let mut dict = StrikeData::default();
1012		dict.insert(6, 0);
1013		let mut table = Ebdt {
1014			version: 2.0,
1015			glyphs: vec![BitmapGlyph::Raw { format: 8, data }],
1016			strike_data: vec![Some(dict)],
1017		};
1018		table.remap_glyphs(&mut |g| Ok(g / 2))?;
1019		let ids = table.strike_data[0].as_ref().map(StrikeData::glyph_ids);
1020		assert_eq!(ids, Some(&[3][..]));
1021		let parsed = table.glyphs[0].parsed()?;
1022		let glyphs: Vec<u32> = parsed
1023			.components
1024			.iter()
1025			.flatten()
1026			.map(|c| c.glyph)
1027			.collect();
1028		assert_eq!(glyphs, [5]);
1029
1030		assert!(table.glyphs[0].is_composite());
1031		table.glyphs[0].ensure_decompiled()?;
1032		table.remap_glyphs(&mut |g| Ok(g / 2))?;
1033		let parsed = table.glyphs[0].parsed()?;
1034		let glyphs: Vec<u32> = parsed
1035			.components
1036			.iter()
1037			.flatten()
1038			.map(|c| c.glyph)
1039			.collect();
1040		assert_eq!(glyphs, [2]);
1041		Ok(())
1042	}
1043
1044	/// UPSTREAM-BUG(B21).
1045	#[test]
1046	fn components_cannot_be_read_from_ttx() -> Result<()> {
1047		let element = |components: &str| {
1048			let text = format!(
1049				"<ebdt_bitmap_format_8 name=\"a\"><components>{components}</components></ebdt_bitmap_format_8>"
1050			);
1051			fontoxide_misc::xml_reader::parse(&text).map_err(|e| Error::ttx(e.to_string()))
1052		};
1053		assert!(ParsedBitmapGlyph::from_xml(8, &element("")?).is_ok());
1054		assert!(ParsedBitmapGlyph::from_xml(8, &element("<ebdtComponent name=\"b\"/>")?).is_err());
1055		Ok(())
1056	}
1057
1058	/// `test_extfile_name_mapping_is_injective`.
1059	#[test]
1060	fn ext_file_names_are_injective() {
1061		let mut names: Vec<String> = [
1062			"a", "b", "uni0041", "a.alt", "%", "%25", "%2Fb", "/b", "a/b", "../b", "..", ".", "",
1063			"x/", "y/", "a\\b", "\u{e9}",
1064		]
1065		.map(str::to_owned)
1066		.to_vec();
1067		names.extend(["a/b", "", ".."].map(ext_file_name));
1068		let mapped: BTreeSet<String> = names.iter().map(|n| ext_file_name(n)).collect();
1069		assert_eq!(mapped.len(), names.iter().collect::<BTreeSet<_>>().len());
1070		assert!(
1071			mapped
1072				.iter()
1073				.all(|m| !m.contains(['/', '\\']) && !matches!(m.as_str(), "" | "." | ".."))
1074		);
1075		assert_eq!(ext_file_name("uni0041"), "uni0041");
1076		assert_eq!(ext_file_name("../b"), "%..%2Fb");
1077	}
1078
1079	#[test]
1080	fn rows_round_trip() -> Result<()> {
1081		for format in [1, 2] {
1082			let mut glyph = ParsedBitmapGlyph {
1083				format,
1084				..Default::default()
1085			};
1086			let rows = vec![vec![0b1010_0000], vec![0b0111_0000]];
1087			glyph.set_rows(rows.clone(), 1, 4, false)?;
1088			for (i, row) in rows.iter().enumerate() {
1089				assert_eq!(&glyph.row(i, 1, 4, false)?, row, "format {format}");
1090			}
1091		}
1092		Ok(())
1093	}
1094}