1use fontoxide_misc::Tag;
5use fontoxide_misc::xml_reader::Element;
6use fontoxide_misc::xml_writer::XmlWriter;
7
8use crate::binary::{Reader, WriteBytes, fit};
9use crate::sstruct::{F16Dot16, I8, U8, U16, U32, Value, eval};
10use crate::table::{Table, TableType, TableXml};
11use crate::{Error, Font, Result};
12
13crate::sstruct! {
14 pub struct EblcHeader = "eblcHeaderFormat" {
16 pub version: f64 = "version" as F16Dot16,
18 pub num_sizes: u32 = "numSizes" as U32,
20 }
21}
22
23crate::sstruct! {
24 pub struct BitmapSizePart1 = "bitmapSizeTableFormatPart1" {
27 pub index_sub_table_array_offset: u32 = "indexSubTableArrayOffset" as U32,
29 pub index_tables_size: u32 = "indexTablesSize" as U32,
31 pub number_of_index_sub_tables: u32 = "numberOfIndexSubTables" as U32,
33 pub color_ref: u32 = "colorRef" as U32,
35 }
36}
37
38crate::sstruct! {
39 pub struct SbitLineMetrics = "sbitLineMetricsFormat" {
41 pub ascender: i8 = "ascender" as I8,
43 pub descender: i8 = "descender" as I8,
45 pub width_max: u8 = "widthMax" as U8,
47 pub caret_slope_numerator: i8 = "caretSlopeNumerator" as I8,
49 pub caret_slope_denominator: i8 = "caretSlopeDenominator" as I8,
51 pub caret_offset: i8 = "caretOffset" as I8,
53 pub min_origin_sb: i8 = "minOriginSB" as I8,
55 pub min_advance_sb: i8 = "minAdvanceSB" as I8,
57 pub max_before_bl: i8 = "maxBeforeBL" as I8,
59 pub min_after_bl: i8 = "minAfterBL" as I8,
61 pub pad1: i8 = "pad1" as I8,
63 pub pad2: i8 = "pad2" as I8,
65 }
66}
67
68crate::sstruct! {
69 pub struct BitmapSizePart2 = "bitmapSizeTableFormatPart2" {
72 pub start_glyph_index: u16 = "startGlyphIndex" as U16,
74 pub end_glyph_index: u16 = "endGlyphIndex" as U16,
76 pub ppem_x: u8 = "ppemX" as U8,
78 pub ppem_y: u8 = "ppemY" as U8,
80 pub bit_depth: u8 = "bitDepth" as U8,
82 pub flags: i8 = "flags" as I8,
84 }
85}
86
87crate::sstruct! {
88 pub struct BigGlyphMetrics = "bigGlyphMetricsFormat" {
90 pub height: u8 = "height" as U8,
92 pub width: u8 = "width" as U8,
94 pub hori_bearing_x: i8 = "horiBearingX" as I8,
96 pub hori_bearing_y: i8 = "horiBearingY" as I8,
98 pub hori_advance: u8 = "horiAdvance" as U8,
100 pub vert_bearing_x: i8 = "vertBearingX" as I8,
102 pub vert_bearing_y: i8 = "vertBearingY" as I8,
104 pub vert_advance: u8 = "vertAdvance" as U8,
106 }
107}
108
109crate::sstruct! {
110 pub struct SmallGlyphMetrics = "smallGlyphMetricsFormat" {
112 pub height: u8 = "height" as U8,
114 pub width: u8 = "width" as U8,
116 pub bearing_x: i8 = "BearingX" as I8,
118 pub bearing_y: i8 = "BearingY" as I8,
120 pub advance: u8 = "Advance" as U8,
122 }
123}
124
125pub(crate) fn metrics_to_xml(writer: &mut XmlWriter, tag: &str, values: Vec<(&str, Value)>) {
128 writer.begintag(tag, &[]);
129 writer.newline();
130 for (name, value) in values {
131 writer.simpletag(name, &[("value", &value)]);
132 writer.newline();
133 }
134 writer.endtag(tag);
135 writer.newline();
136}
137
138pub(crate) fn literal(element: &Element) -> Result<fontoxide_misc::text_tools::Literal> {
140 eval(required_attr(element, "value")?)
141}
142
143pub(crate) fn required_attr<'a>(element: &'a Element, name: &str) -> Result<&'a str> {
145 element
146 .attr(name)
147 .ok_or_else(|| Error::ttx(format!("missing '{name}' on <{}>", element.name)))
148}
149
150pub(crate) fn int_attr<T: TryFrom<i128>>(element: &Element, name: &str) -> Result<T> {
152 let value = eval(required_attr(element, name)?)?
153 .as_int()
154 .ok_or_else(|| Error::value(format!("invalid value for {name}")))?;
155 fit(value, name)
156}
157
158const INDEX_SUB_HEADER_SIZE: usize = 8;
160
161pub(crate) fn clip(data: &[u8], start: u64, end: u64) -> &[u8] {
163 let len = data.len() as u64;
164 let end = end.min(len);
165 let start = start.min(end);
166 &data[start as usize..end as usize]
167}
168
169#[derive(Debug, Clone, PartialEq, Default)]
171pub struct IndexSubTable {
172 pub index_format: u16,
174 pub image_format: u16,
176 pub image_data_offset: u32,
178 pub first_glyph_index: u32,
180 pub last_glyph_index: u32,
182 pub additional_offset: u32,
184 pub image_size: Option<u32>,
186 pub metrics: Option<BigGlyphMetrics>,
188 pub names: Vec<u32>,
190 pub locations: Vec<(u64, u64)>,
193}
194
195fn is_fixed_size(index_format: u16) -> bool {
196 matches!(index_format, 2 | 5)
197}
198
199fn offset_size(index_format: u16) -> Option<usize> {
200 match index_format {
201 1 => Some(4),
202 3 => Some(2),
203 _ => None,
204 }
205}
206
207impl IndexSubTable {
208 fn decompile(&mut self, data: &[u8]) -> Result<()> {
209 match self.index_format {
210 1 | 3 => self.decompile_offsets(data),
211 2 => self.decompile_format2(data),
212 4 => self.decompile_format4(data),
213 5 => self.decompile_format5(data),
214 f => Err(Error::ttlib(format!("KeyError: {f}"))),
215 }
216 }
217
218 fn decompile_offsets(&mut self, data: &[u8]) -> Result<()> {
220 let num_glyphs = i64::from(self.last_glyph_index) - i64::from(self.first_glyph_index) + 1;
221 let count = (num_glyphs + 1).max(0) as usize;
222 let mut r = Reader::new(data);
223 let offsets: Vec<u64> = if self.index_format == 1 {
224 r.u32_array(count)?.into_iter().map(u64::from).collect()
225 } else {
226 r.u16_array(count)?.into_iter().map(u64::from).collect()
227 };
228 let base = u64::from(self.image_data_offset);
229 let mut names = Vec::new();
231 let mut locations = Vec::new();
232 for (gid, pair) in (self.first_glyph_index..=self.last_glyph_index).zip(offsets.windows(2))
233 {
234 let (start, end) = (pair[0] + base, pair[1] + base);
235 if start < end {
236 names.push(gid);
237 locations.push((start, end));
238 }
239 }
240 if names.is_empty() {
241 return Err(Error::value(
242 "not enough values to unpack (expected 2, got 0)",
243 ));
244 }
245 self.names = names;
246 self.locations = locations;
247 Ok(())
248 }
249
250 fn fixed_locations(&self, count: usize) -> Vec<(u64, u64)> {
252 let size = u64::from(self.image_size.unwrap_or_default());
253 let base = u64::from(self.image_data_offset);
254 (0..count as u64)
255 .map(|i| (size * i + base, size * (i + 1) + base))
256 .collect()
257 }
258
259 fn decompile_format2(&mut self, data: &[u8]) -> Result<()> {
260 let mut r = Reader::new(data);
261 self.image_size = Some(r.u32()?);
262 let (metrics, _) = BigGlyphMetrics::unpack2(r.rest())?;
263 self.metrics = Some(metrics);
264 self.names = (self.first_glyph_index..=self.last_glyph_index).collect();
265 self.locations = self.fixed_locations(self.names.len());
266 Ok(())
267 }
268
269 fn decompile_format4(&mut self, data: &[u8]) -> Result<()> {
270 let mut r = Reader::new(data);
271 let num_glyphs = r.u32()? as usize;
272 let pairs = r.u16_array((num_glyphs + 1).saturating_mul(2))?;
273 let base = u64::from(self.image_data_offset);
274 let pairs = pairs.as_chunks::<2>().0;
275 let offsets: Vec<u64> = pairs.iter().map(|p| u64::from(p[1]) + base).collect();
276 self.locations = offsets.windows(2).map(|p| (p[0], p[1])).collect();
277 self.names = pairs
278 .iter()
279 .take(num_glyphs)
280 .map(|p| u32::from(p[0]))
281 .collect();
282 Ok(())
283 }
284
285 fn decompile_format5(&mut self, data: &[u8]) -> Result<()> {
286 let mut r = Reader::new(data);
287 self.image_size = Some(r.u32()?);
288 self.metrics = Some(BigGlyphMetrics::unpack(&mut r)?);
289 let num_glyphs = r.u32()? as usize;
290 self.names = r
291 .u16_array(num_glyphs)?
292 .into_iter()
293 .map(u32::from)
294 .collect();
295 self.locations = self.fixed_locations(self.names.len());
296 Ok(())
297 }
298
299 fn compile(&mut self) -> Result<Vec<u8>> {
300 match self.index_format {
301 1 | 3 => self.compile_offsets(),
302 2 => self.compile_format2(),
303 4 => self.compile_format4(),
304 5 => self.compile_format5(),
305 f => Err(Error::ttlib(format!("KeyError: {f}"))),
306 }
307 }
308
309 fn compile_header(&self, out: &mut Vec<u8>) {
311 out.put_u16(self.index_format);
312 out.put_u16(self.image_format);
313 out.put_u32(self.image_data_offset);
314 }
315
316 fn check_consecutive(&self) -> Result<()> {
317 if self.locations.windows(2).any(|l| l[0].1 != l[1].0) {
318 return Err(Error::Assertion(
319 "Data must be consecutive in indexSubTable".into(),
320 ));
321 }
322 Ok(())
323 }
324
325 fn min_start(&self) -> Result<u32> {
327 let min = self
328 .locations
329 .iter()
330 .map(|l| l.0)
331 .min()
332 .ok_or_else(|| Error::ttlib("StopIteration"))?;
333 fit(min, "imageDataOffset")
334 }
335
336 fn compile_offsets(&mut self) -> Result<Vec<u8>> {
338 self.check_consecutive()?;
339 if self.names.windows(2).any(|g| g[0] >= g[1]) {
340 return Err(Error::Assertion("glyph IDs must increase".into()));
341 }
342 let index_error = || Error::ttlib("IndexError: deque index out of range");
343 let mut all = Vec::new();
345 let (mut next_name, mut next_location) = (0, 0);
346 for gid in self.first_glyph_index..=self.last_glyph_index {
347 let location = *self.locations.get(next_location).ok_or_else(index_error)?;
348 if gid == *self.names.get(next_name).ok_or_else(index_error)? {
349 next_name += 1;
350 next_location += 1;
351 all.push(location);
352 } else {
353 all.push((location.0, location.0));
354 }
355 }
356 let first = all.first().ok_or_else(index_error)?;
357 let mut offsets = vec![first.0, first.1];
358 offsets.extend(all[1..].iter().map(|l| l.1));
359 let min = offsets.iter().copied().min().unwrap_or_default();
360 self.image_data_offset = fit(min, "imageDataOffset")?;
361
362 let mut out = Vec::new();
363 self.compile_header(&mut out);
364 let size = offset_size(self.index_format).unwrap_or(4);
365 for offset in &offsets {
366 let value = offset - min;
367 if size == 4 {
368 out.put_u32(fit(value, "offset")?);
369 } else {
370 out.put_u16(fit(value, "offset")?);
371 }
372 }
373 if !(size * offsets.len()).is_multiple_of(4) {
374 out.put_u16(0);
375 }
376 Ok(out)
377 }
378
379 fn compile_metrics(&self, out: &mut Vec<u8>) -> Result<()> {
380 out.put_u32(self.image_size.ok_or_else(|| missing("imageSize"))?);
381 self.metrics
382 .as_ref()
383 .ok_or_else(|| missing("metrics"))?
384 .pack(out)
385 }
386
387 fn compile_format2(&mut self) -> Result<Vec<u8>> {
388 let expected = (self.first_glyph_index..=self.last_glyph_index).collect::<Vec<_>>();
389 if self.names != expected {
390 return Err(Error::Assertion("Format 2 ids must be consecutive.".into()));
391 }
392 self.image_data_offset = self.min_start()?;
393 let mut out = Vec::new();
394 self.compile_header(&mut out);
395 self.compile_metrics(&mut out)?;
396 Ok(out)
397 }
398
399 fn compile_format4(&mut self) -> Result<Vec<u8>> {
400 self.check_consecutive()?;
401 let first = self
402 .locations
403 .first()
404 .ok_or_else(|| Error::ttlib("IndexError: list index out of range"))?;
405 let mut offsets = vec![first.0, first.1];
406 offsets.extend(self.locations[1..].iter().map(|l| l.1));
407 let min = offsets.iter().copied().min().unwrap_or_default();
408 self.image_data_offset = fit(min, "imageDataOffset")?;
409
410 let mut out = Vec::new();
411 self.compile_header(&mut out);
412 out.put_u32(fit(self.names.len(), "numGlyphs")?);
413 let ids = self.names.iter().copied().chain([0]);
414 for (gid, offset) in ids.zip(&offsets) {
415 out.put_u16(fit(gid, "glyphCode")?);
416 out.put_u16(fit(offset - min, "offset")?);
417 }
418 Ok(out)
419 }
420
421 fn compile_format5(&mut self) -> Result<Vec<u8>> {
422 self.image_data_offset = self.min_start()?;
423 let mut out = Vec::new();
424 self.compile_header(&mut out);
425 self.compile_metrics(&mut out)?;
426 out.put_u32(fit(self.names.len(), "numGlyphs")?);
427 for &gid in &self.names {
428 out.put_u16(fit(gid, "glyphCode")?);
429 }
430 if self.names.len() % 2 == 1 {
431 out.put_u16(0);
432 }
433 Ok(out)
434 }
435
436 pub(crate) fn pad_bitmap_data(&self, mut data: Vec<u8>) -> Result<Vec<u8>> {
438 if is_fixed_size(self.index_format) {
439 let size = self.image_size.ok_or_else(|| missing("imageSize"))? as usize;
440 if data.len() > size {
441 return Err(Error::Assertion(format!(
442 "Data in indexSubTable format {} must be less than the fixed size.",
443 self.index_format
444 )));
445 }
446 data.resize(size, 0);
447 }
448 Ok(data)
449 }
450
451 fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font) -> Result<()> {
452 let tag = format!("eblc_index_sub_table_{}", self.index_format);
453 writer.begintag_ordered(
454 &tag,
455 &[
456 ("imageFormat", &self.image_format),
457 ("firstGlyphIndex", &self.first_glyph_index),
458 ("lastGlyphIndex", &self.last_glyph_index),
459 ],
460 );
461 writer.newline();
462 if is_fixed_size(self.index_format) {
463 let size = self.image_size.ok_or_else(|| missing("imageSize"))?;
464 writer.simpletag("imageSize", &[("value", &size)]);
465 writer.newline();
466 let metrics = self.metrics.as_ref().ok_or_else(|| missing("metrics"))?;
467 metrics_to_xml(writer, "BigGlyphMetrics", metrics.values());
468 }
469 let order = font.glyph_order()?;
470 for &gid in &self.names {
471 writer.simpletag("glyphLoc", &[("name", &order.name(gid)), ("id", &gid)]);
472 writer.newline();
473 }
474 writer.endtag(&tag);
475 writer.newline();
476 Ok(())
477 }
478
479 fn from_xml(index_format: u16, element: &Element, font: &mut Font) -> Result<Self> {
480 if !matches!(index_format, 1..=5) {
481 return Err(Error::ttlib(format!("KeyError: {index_format}")));
482 }
483 let mut t = IndexSubTable {
484 index_format,
485 image_format: int_attr(element, "imageFormat")?,
486 first_glyph_index: int_attr(element, "firstGlyphIndex")?,
487 last_glyph_index: int_attr(element, "lastGlyphIndex")?,
488 ..Default::default()
489 };
490 for child in element.elements() {
491 match child.name.as_str() {
492 "imageSize" if is_fixed_size(index_format) => {
493 t.image_size = Some(int_attr(child, "value")?);
494 }
495 "BigGlyphMetrics" if is_fixed_size(index_format) => {
496 let mut metrics = BigGlyphMetrics::default();
497 for m in child.elements() {
498 if !metrics.set_literal(&m.name, &literal(m)?)? {
499 log::warn!(
500 "unknown name '{}' being ignored in BigGlyphMetrics.",
501 m.name
502 );
503 }
504 }
505 t.metrics = Some(metrics);
506 }
507 "SmallGlyphMetrics" if is_fixed_size(index_format) => {
508 log::warn!("SmallGlyphMetrics being ignored in format {index_format}.");
509 }
510 "glyphLoc" => t.names.push(font.glyph_id(required_attr(child, "name")?)?),
511 _ => {}
512 }
513 }
514 Ok(t)
515 }
516}
517
518fn missing(attribute: &str) -> Error {
519 Error::ttlib(format!("AttributeError: {attribute}"))
520}
521
522#[derive(Debug, Clone, PartialEq, Default)]
526pub struct BitmapSizeTable {
527 pub part1: BitmapSizePart1,
529 pub hori: SbitLineMetrics,
531 pub vert: SbitLineMetrics,
533 pub part2: BitmapSizePart2,
535}
536
537impl BitmapSizeTable {
538 fn to_xml(&self, writer: &mut XmlWriter) {
539 writer.begintag("bitmapSizeTable", &[]);
540 writer.newline();
541 for (name, metrics) in [("hori", &self.hori), ("vert", &self.vert)] {
542 writer.begintag_ordered("sbitLineMetrics", &[("direction", &name)]);
543 writer.newline();
544 for (field, value) in metrics.values() {
545 writer.simpletag(field, &[("value", &value)]);
546 writer.newline();
547 }
548 writer.endtag("sbitLineMetrics");
549 writer.newline();
550 }
551 let part1 = self.part1.values().into_iter().skip(3);
553 for (field, value) in part1.chain(self.part2.values()) {
554 writer.simpletag(field, &[("value", &value)]);
555 writer.newline();
556 }
557 writer.endtag("bitmapSizeTable");
558 writer.newline();
559 }
560
561 fn read_xml(&mut self, element: &Element) -> Result<()> {
562 for child in element.elements() {
563 if child.name == "sbitLineMetrics" {
564 let direction = required_attr(child, "direction")?;
565 let mut metrics = SbitLineMetrics::default();
566 for m in child.elements() {
567 if SbitLineMetrics::FIELDS.iter().any(|f| f.name == m.name) {
568 metrics.set_literal(&m.name, &literal(m)?)?;
569 }
570 }
571 match direction {
572 "hori" => self.hori = metrics,
573 "vert" => self.vert = metrics,
574 _ => {
575 return Err(Error::Assertion(
576 "SbitLineMetrics direction specified invalid.".into(),
577 ));
578 }
579 }
580 } else if child.name == "colorRef" {
581 self.part1.color_ref = int_attr(child, "value")?;
582 } else if BitmapSizePart2::FIELDS.iter().any(|f| f.name == child.name) {
583 self.part2.set_literal(&child.name, &literal(child)?)?;
584 } else {
585 log::warn!(
586 "unknown name '{}' being ignored in BitmapSizeTable.",
587 child.name
588 );
589 }
590 }
591 Ok(())
592 }
593}
594
595#[derive(Debug, Clone, PartialEq, Default)]
597pub struct Strike {
598 pub bitmap_size_table: BitmapSizeTable,
600 pub index_sub_tables: Vec<IndexSubTable>,
602}
603
604#[derive(Debug, Clone, PartialEq, Default)]
611pub struct BitmapLocator<const COLOR: bool, const APPLE: bool = false> {
612 pub version: f64,
614 pub strikes: Vec<Option<Strike>>,
617}
618
619pub type Eblc = BitmapLocator<false>;
621pub type Cblc = BitmapLocator<true>;
623pub type Bloc = BitmapLocator<false, true>;
625
626impl<const COLOR: bool, const APPLE: bool> TableType for BitmapLocator<COLOR, APPLE> {
627 const TAG: Tag = if COLOR {
628 Tag::new(b"CBLC")
629 } else if APPLE {
630 Tag::new(b"bloc")
631 } else {
632 Tag::new(b"EBLC")
633 };
634
635 fn decompile(data: &[u8], _font: &mut Font) -> Result<Self> {
636 let (header, _) = EblcHeader::unpack2(clip(data, 0, 8))?;
637 let mut pos = 8;
638 let mut strikes = Vec::new();
639 for _ in 0..header.num_sizes {
640 let rest = clip(data, pos, u64::MAX);
641 let (part1, rest) = BitmapSizePart1::unpack2(rest)?;
642 let (hori, rest) = SbitLineMetrics::unpack2(rest)?;
643 let (vert, rest) = SbitLineMetrics::unpack2(rest)?;
644 let (part2, _) = BitmapSizePart2::unpack2(rest)?;
645 pos += 48;
646 strikes.push(Strike {
647 bitmap_size_table: BitmapSizeTable {
648 part1,
649 hori,
650 vert,
651 part2,
652 },
653 index_sub_tables: Vec::new(),
654 });
655 }
656 for strike in &mut strikes {
657 let part1 = &strike.bitmap_size_table.part1;
658 let array_offset = u64::from(part1.index_sub_table_array_offset);
659 for i in 0..u64::from(part1.number_of_index_sub_tables) {
660 let entry = array_offset + i * INDEX_SUB_HEADER_SIZE as u64;
661 let mut r = Reader::new(clip(data, entry, entry + 8));
662 if r.remaining() != INDEX_SUB_HEADER_SIZE {
663 return Err(Error::Struct(
664 "unpack requires a buffer of 8 bytes".to_owned(),
665 ));
666 }
667 let first_glyph_index = u32::from(r.u16()?);
668 let last_glyph_index = u32::from(r.u16()?);
669 let additional_offset = r.u32()?;
670
671 let start = array_offset + u64::from(additional_offset);
672 let mut r = Reader::new(clip(data, start, start + 8));
673 if r.remaining() != INDEX_SUB_HEADER_SIZE {
674 return Err(Error::Struct(
675 "unpack requires a buffer of 8 bytes".to_owned(),
676 ));
677 }
678 let mut table = IndexSubTable {
679 index_format: r.u16()?,
680 image_format: r.u16()?,
681 image_data_offset: r.u32()?,
682 first_glyph_index,
683 last_glyph_index,
684 additional_offset,
685 ..Default::default()
686 };
687 table.decompile(clip(data, start + 8, u64::MAX))?;
688 strike.index_sub_tables.push(table);
689 }
690 }
691 Ok(BitmapLocator {
692 version: header.version,
693 strikes: strikes.into_iter().map(Some).collect(),
694 })
695 }
696}
697
698impl<const COLOR: bool, const APPLE: bool> BitmapLocator<COLOR, APPLE> {
699 fn compile_table(&mut self) -> Result<Vec<u8>> {
700 let mut sub_table_data = Vec::new();
701 let mut data_size = 8 + self.strikes.len() * 48;
702 for strike in &mut self.strikes {
703 let strike = strike.as_mut().ok_or_else(|| missing("bitmapSizeTable"))?;
704 let count = strike.index_sub_tables.len();
705 let array_offset = data_size;
706 data_size += count * INDEX_SUB_HEADER_SIZE;
707
708 let mut sub_tables = Vec::with_capacity(count);
709 for table in &mut strike.index_sub_tables {
710 table.additional_offset =
711 fit(data_size - array_offset, "additionalOffsetToIndexSubtable")?;
712 let empty = || Error::value("min() arg is an empty sequence");
713 table.first_glyph_index = *table.names.iter().min().ok_or_else(empty)?;
714 table.last_glyph_index = *table.names.iter().max().ok_or_else(empty)?;
715 let data = table.compile()?;
716 data_size += data.len();
717 sub_tables.push(data);
718 }
719 let tables = &strike.index_sub_tables;
720 let empty = || Error::value("min() arg is an empty sequence");
721 let first = tables
722 .iter()
723 .map(|t| t.first_glyph_index)
724 .min()
725 .ok_or_else(empty)?;
726 let last = tables
727 .iter()
728 .map(|t| t.last_glyph_index)
729 .max()
730 .ok_or_else(empty)?;
731 let size_table = &mut strike.bitmap_size_table;
732 size_table.part1.number_of_index_sub_tables = fit(count, "numberOfIndexSubTables")?;
733 size_table.part1.index_sub_table_array_offset =
734 fit(array_offset, "indexSubTableArrayOffset")?;
735 size_table.part2.start_glyph_index = fit(first, "startGlyphIndex")?;
736 size_table.part2.end_glyph_index = fit(last, "endGlyphIndex")?;
737 size_table.part1.index_tables_size = fit(data_size - array_offset, "indexTablesSize")?;
738
739 for table in tables {
740 sub_table_data.put_u16(fit(table.first_glyph_index, "firstGlyphIndex")?);
741 sub_table_data.put_u16(fit(table.last_glyph_index, "lastGlyphIndex")?);
742 sub_table_data.put_u32(table.additional_offset);
743 }
744 sub_table_data.extend(sub_tables.into_iter().flatten());
745 }
746
747 let mut out = Vec::with_capacity(data_size);
748 EblcHeader {
749 version: self.version,
750 num_sizes: fit(self.strikes.len(), "numSizes")?,
751 }
752 .pack(&mut out)?;
753 for strike in self.strikes.iter().flatten() {
754 let size_table = &strike.bitmap_size_table;
755 size_table.part1.pack(&mut out)?;
756 size_table.hori.pack(&mut out)?;
757 size_table.vert.pack(&mut out)?;
758 size_table.part2.pack(&mut out)?;
759 }
760 out.extend(sub_table_data);
761 Ok(out)
762 }
763}
764
765impl<const COLOR: bool, const APPLE: bool> Table for BitmapLocator<COLOR, APPLE> {
766 fn tag(&self) -> Tag {
767 Self::TAG
768 }
769
770 fn compile(&mut self, _font: &mut Font) -> Result<Vec<u8>> {
771 self.compile_table()
772 }
773
774 fn clone_table(&self) -> Box<dyn Table> {
775 Box::new(self.clone())
776 }
777
778 fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
780 for strike in self.strikes.iter_mut().flatten() {
781 for table in &mut strike.index_sub_tables {
782 for name in &mut table.names {
783 *name = f(*name)?;
784 }
785 }
786 }
787 Ok(())
788 }
789}
790
791impl<const COLOR: bool, const APPLE: bool> TableXml for BitmapLocator<COLOR, APPLE> {
792 fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font) -> Result<()> {
793 writer.simpletag_ordered("header", &[("version", &Value::Float(self.version))]);
794 writer.newline();
795 for (index, strike) in self.strikes.iter().enumerate() {
796 let strike = strike.as_ref().ok_or_else(|| missing("toXML"))?;
797 writer.begintag_ordered("strike", &[("index", &index)]);
798 writer.newline();
799 strike.bitmap_size_table.to_xml(writer);
800 writer.comment(
801 "GlyphIds are written but not read. The firstGlyphIndex and\nlastGlyphIndex values will be recalculated by the compiler.",
802 );
803 writer.newline();
804 for table in &strike.index_sub_tables {
805 table.to_xml(writer, font)?;
806 }
807 writer.endtag("strike");
808 writer.newline();
809 }
810 Ok(())
811 }
812
813 fn from_xml(&mut self, element: &Element, font: &mut Font) -> Result<()> {
814 match element.name.as_str() {
815 "header" => {
816 self.version = eval(required_attr(element, "version")?)?
817 .as_float()
818 .ok_or_else(|| Error::value("invalid value for version"))?;
819 }
820 "strike" => {
821 let index: usize = int_attr(element, "index")?;
822 let mut strike = Strike::default();
823 for child in element.elements() {
824 if child.name == "bitmapSizeTable" {
825 strike.bitmap_size_table.read_xml(child)?;
826 } else if let Some(format) = child.name.strip_prefix("eblc_index_sub_table_") {
827 let format = eval(format)?
828 .as_int()
829 .ok_or_else(|| Error::value("invalid index format"))?;
830 strike.index_sub_tables.push(IndexSubTable::from_xml(
831 fit(format, "indexFormat")?,
832 child,
833 font,
834 )?);
835 }
836 }
837 if index >= self.strikes.len() {
838 self.strikes.resize(index + 1, None);
839 }
840 if self.strikes[index].is_some() {
841 return Err(Error::Assertion("Duplicate strike EBLC indices.".into()));
842 }
843 self.strikes[index] = Some(strike);
844 }
845 _ => {}
846 }
847 Ok(())
848 }
849}
850
851#[cfg(test)]
852mod tests {
853 use super::*;
854
855 #[test]
856 fn formats_match_upstream() {
857 use crate::sstruct::tests::check;
858 check(EblcHeader::FORMAT_NAME, EblcHeader::FIELDS);
859 check(BitmapSizePart1::FORMAT_NAME, BitmapSizePart1::FIELDS);
860 check(SbitLineMetrics::FORMAT_NAME, SbitLineMetrics::FIELDS);
861 check(BitmapSizePart2::FORMAT_NAME, BitmapSizePart2::FIELDS);
862 check(BigGlyphMetrics::FORMAT_NAME, BigGlyphMetrics::FIELDS);
863 check(SmallGlyphMetrics::FORMAT_NAME, SmallGlyphMetrics::FIELDS);
864 }
865}