1use crate::model::Error;
4use crate::{
5 model::glyph::outline::PathSink,
6 ps::{
7 cff::{
8 blend::BlendState, charset::Charset, dict, encoding::Encoding as RawEncoding,
9 fd_select::FdSelect, index::Index,
10 },
11 charstring::{self, CommandSink, NopFilterSink, TransformSink},
12 encoding::PredefinedEncoding,
13 hinting::HintingParams,
14 string::Sid,
15 transform::{ScaledFontMatrix, Transform},
16 },
17 tables::{cff, cff2, variations::ItemVariationStore},
18 FontData, FontRead,
19};
20use core::ops::Range;
21use types::{BoundingBox, F2Dot14, Fixed, GlyphId};
22use yoke::Yokeable;
23
24#[derive(Clone, Yokeable)]
29pub struct CffFontRef<'a> {
30 data: &'a [u8],
31 is_cff2: bool,
32 upem: i32,
33 global_subrs: Index<'a>,
34 top_dict: TopDict<'a>,
35 top_dict_index: u16,
36}
37
38impl<'a> CffFontRef<'a> {
39 #[cfg(test)]
42 pub(crate) fn sid_private_dict_range(&self) -> Option<Range<usize>> {
43 match &self.top_dict.kind {
44 CffFontKind::Sid { private_dict, .. } => {
45 Some(private_dict.start as usize..private_dict.end as usize)
46 }
47 _ => None,
48 }
49 }
50
51 pub fn new(data: &'a [u8], top_dict_index: u32, upem: Option<i32>) -> Result<Self, Error> {
59 let version: u8 = FontData::new(data).read_at(0)?;
60 match version {
61 1 => Self::new_cff(data, top_dict_index, upem),
62 2 => Self::new_cff2(data, upem),
63 _ => Err(Error::Malformed),
65 }
66 }
67
68 pub fn new_cff(data: &'a [u8], top_dict_index: u32, upem: Option<i32>) -> Result<Self, Error> {
73 let cff = cff::Cff::read(data.into())?;
74 let top_dict_data = cff
75 .top_dicts()
76 .get(top_dict_index as usize)
77 .ok_or(Error::Malformed)?;
78 let top_dict_index: u16 = top_dict_index.try_into().map_err(|_| Error::Malformed)?;
79 Self::new_impl(
80 data,
81 false,
82 upem,
83 top_dict_data,
84 top_dict_index,
85 cff.strings().into(),
86 cff.global_subrs().into(),
87 )
88 }
89
90 pub fn new_cff2(data: &'a [u8], upem: Option<i32>) -> Result<Self, Error> {
95 let cff = cff2::Cff2::read(data.into())?;
96 Self::new_impl(
97 data,
98 true,
99 upem,
100 cff.top_dict_data(),
101 0,
102 Index::Empty,
103 cff.global_subrs().into(),
104 )
105 }
106
107 fn new_impl(
108 data: &'a [u8],
109 is_cff2: bool,
110 upem: Option<i32>,
111 top_dict_data: &'a [u8],
112 top_dict_index: u16,
113 strings: Index<'a>,
114 global_subrs: Index<'a>,
115 ) -> Result<Self, Error> {
116 let top_dict = TopDict::new(data, top_dict_data, strings, is_cff2)?;
117 let top_upem = top_dict.matrix.map(|mat| mat.scale).unwrap_or(1000);
118 Ok(Self {
119 data,
120 is_cff2,
121 upem: upem.unwrap_or(top_upem),
122 global_subrs,
123 top_dict,
124 top_dict_index,
125 })
126 }
127
128 pub fn data(&self) -> &'a [u8] {
130 self.data
131 }
132
133 pub fn version(&self) -> u16 {
135 if self.is_cff2 {
136 2
137 } else {
138 1
139 }
140 }
141
142 pub fn metadata(&self) -> Option<Metadata<'a>> {
144 Metadata::new(self.data, self.top_dict_index)
145 }
146
147 pub fn is_cid(&self) -> bool {
149 matches!(&self.top_dict.kind, CffFontKind::Cid { .. })
150 }
151
152 pub fn global_subrs(&self) -> &Index<'a> {
154 &self.global_subrs
155 }
156
157 pub fn num_glyphs(&self) -> u32 {
159 self.top_dict.charstrings.count()
160 }
161
162 pub fn charstrings(&self) -> &Index<'a> {
164 &self.top_dict.charstrings
165 }
166
167 pub fn strings(&self) -> Option<&Index<'a>> {
169 match &self.top_dict.kind {
170 CffFontKind::Sid { strings, .. } => Some(strings),
171 _ => None,
172 }
173 }
174
175 pub fn string(&self, sid: Sid) -> Option<&'a [u8]> {
177 match sid.resolve_standard() {
178 Ok(s) => Some(s),
179 Err(idx) => self.strings()?.get(idx),
180 }
181 }
182
183 pub fn charset(&self) -> Option<Charset<'a>> {
188 Charset::new(
189 self.data.into(),
190 self.top_dict.charset_offset.get()?,
191 self.top_dict.charstrings.count(),
192 )
193 }
194
195 pub fn encoding(&self) -> Option<Encoding<'a>> {
197 let charset = self.charset()?;
198 let encoding = RawEncoding::new(self.data, self.top_dict.encoding_offset.get()?)?;
199 Some(Encoding { encoding, charset })
200 }
201
202 pub fn matrix(&self) -> Option<&ScaledFontMatrix> {
204 self.top_dict.matrix.as_ref()
205 }
206
207 pub fn upem(&self) -> i32 {
209 self.upem
210 }
211
212 pub fn var_store(&self) -> Option<&ItemVariationStore<'a>> {
216 self.top_dict.var_store.as_ref()
217 }
218
219 pub fn num_subfonts(&self) -> u16 {
221 match &self.top_dict.kind {
222 CffFontKind::Sid { .. } => 1,
223 CffFontKind::Cid { fd_array, .. } | CffFontKind::Cff2 { fd_array, .. } => {
224 fd_array.count() as u16
225 }
226 }
227 }
228
229 pub fn subfont_index(&self, gid: GlyphId) -> Option<u16> {
231 match &self.top_dict.kind {
232 CffFontKind::Sid { .. } => Some(0),
233 CffFontKind::Cid { fd_select, .. } | CffFontKind::Cff2 { fd_select, .. } => fd_select
234 .as_ref()
235 .map_or(Some(0), |fds| fds.font_index(gid)),
236 }
237 }
238
239 pub fn subfont(&self, index: u16, coords: &[F2Dot14]) -> Result<Subfont, Error> {
242 let blend = self.blend_state(0, coords);
243 match &self.top_dict.kind {
244 CffFontKind::Sid { private_dict, .. } => Subfont::new(
245 self.data,
246 private_dict.start as usize..private_dict.end as usize,
247 blend,
248 None,
249 ),
250 CffFontKind::Cid { fd_array, .. } | CffFontKind::Cff2 { fd_array, .. } => {
251 let font_dict =
252 FontDict::new(fd_array.get(index as usize).ok_or(Error::Malformed)?)?;
253 Subfont::new(
254 self.data,
255 font_dict.private_dict_range,
256 blend,
257 font_dict.matrix,
258 )
259 }
260 }
261 }
262
263 pub fn subfont_hinted(
266 &self,
267 index: u16,
268 coords: &[F2Dot14],
269 ) -> Result<(Subfont, HintingParams), Error> {
270 let blend = self.blend_state(0, coords);
271 match &self.top_dict.kind {
272 CffFontKind::Sid { private_dict, .. } => Subfont::new_hinted(
273 self.data,
274 private_dict.start as usize..private_dict.end as usize,
275 blend,
276 None,
277 ),
278 CffFontKind::Cid { fd_array, .. } | CffFontKind::Cff2 { fd_array, .. } => {
279 let font_dict =
280 FontDict::new(fd_array.get(index as usize).ok_or(Error::Malformed)?)?;
281 Subfont::new_hinted(
282 self.data,
283 font_dict.private_dict_range,
284 blend,
285 font_dict.matrix,
286 )
287 }
288 }
289 }
290
291 pub fn transform(&self, subfont: &Subfont, ppem: Option<f32>) -> Transform {
294 let mut scale = ppem.map(|ppem| Transform::compute_scale(ppem, self.upem));
295 let scaled_matrix = if let Some(top_matrix) = self.top_dict.matrix {
298 if let Some(sub_matrix) = subfont.matrix {
300 Some(top_matrix.combine(&sub_matrix))
301 } else {
302 Some(top_matrix)
304 }
305 } else {
306 subfont.matrix.map(|matrix| matrix.normalize())
308 };
309 if let Some(matrix) = scaled_matrix.as_ref() {
312 if matrix.scale != self.upem {
315 let original_scale = scale.unwrap_or(Fixed::from_i32(64));
319 scale = Some(
320 original_scale
321 .mul_div(Fixed::from_bits(self.upem), Fixed::from_bits(matrix.scale)),
322 );
323 }
324 }
325 Transform {
326 matrix: scaled_matrix
327 .map(|scaled_mat| scaled_mat.matrix)
328 .unwrap_or_default(),
329 scale,
330 }
331 }
332
333 pub fn evaluate_width(
352 &self,
353 subfont: &Subfont,
354 gid: GlyphId,
355 coords: &[F2Dot14],
356 ) -> Result<Option<Fixed>, Error> {
357 let transform = self.transform(subfont, None);
358 Ok(self
359 .charstring_width(subfont, gid, coords)?
360 .map(|width| transform.transform_h_metric(width)))
361 }
362
363 fn charstring_width(
368 &self,
369 subfont: &Subfont,
370 gid: GlyphId,
371 coords: &[F2Dot14],
372 ) -> Result<Option<Fixed>, Error> {
373 let charstrings = self.top_dict.charstrings.clone();
374 let blend = self.blend_state(subfont.vs_index, coords);
375 let subrs = if subfont.subrs_offset != 0 {
376 let data = self
377 .data
378 .get(subfont.subrs_offset as usize..)
379 .ok_or(Error::Malformed)?;
380 Index::new(data, self.is_cff2)?
381 } else {
382 Index::Empty
383 };
384 let charstring_data = charstrings
385 .get(gid.to_u32() as usize)
386 .ok_or(Error::Malformed)?;
387 let ctx = (self.data, &charstrings, &self.global_subrs, &subrs);
388 Ok(
389 match charstring::evaluate_width(&ctx, blend, charstring_data)? {
390 Some(width) => Some(width + subfont.nominal_width),
391 None => subfont.default_width,
392 },
393 )
394 }
395
396 pub fn evaluate_charstring(
403 &self,
404 subfont: &Subfont,
405 gid: GlyphId,
406 coords: &[F2Dot14],
407 sink: &mut impl CommandSink,
408 ) -> Result<Option<Fixed>, Error> {
409 let charstrings = self.top_dict.charstrings.clone();
410 let blend = self.blend_state(subfont.vs_index, coords);
411 let subrs = if subfont.subrs_offset != 0 {
412 let data = self
413 .data
414 .get(subfont.subrs_offset as usize..)
415 .ok_or(Error::Malformed)?;
416 Index::new(data, self.is_cff2)?
417 } else {
418 Index::Empty
419 };
420 let charstring_data = charstrings
421 .get(gid.to_u32() as usize)
422 .ok_or(Error::Malformed)?;
423 let ctx = (self.data, &charstrings, &self.global_subrs, &subrs);
424 if let Some(width) = charstring::evaluate(&ctx, blend, charstring_data, sink)? {
425 Ok(Some(width + subfont.nominal_width))
426 } else {
427 Ok(subfont.default_width)
428 }
429 }
430
431 pub fn advance(
437 &self,
438 subfont: &Subfont,
439 gid: GlyphId,
440 coords: &[F2Dot14],
441 ppem: Option<f32>,
442 ) -> Result<Option<f32>, Error> {
443 let transform = self.transform(subfont, ppem);
444 Ok(self
445 .charstring_width(subfont, gid, coords)?
446 .map(|width| transform.transform_h_metric(width).to_f32().max(0.0)))
447 }
448
449 pub fn evaluate_extents(
471 &self,
472 subfont: &Subfont,
473 gid: GlyphId,
474 coords: &[F2Dot14],
475 ) -> Result<Option<BoundingBox<Fixed>>, Error> {
476 let mut bounds = charstring::ControlBoundsSink::new();
477 let mut nop_filter = charstring::NopFilterSink::new(&mut bounds);
478 let transform = self.transform(subfont, None);
479 let mut transformer = charstring::TransformSink::new(&mut nop_filter, transform);
480 self.evaluate_charstring(subfont, gid, coords, &mut transformer)?;
481 Ok(bounds.bounding_box())
482 }
483
484 pub fn extents(
498 &self,
499 subfont: &Subfont,
500 gid: GlyphId,
501 coords: &[F2Dot14],
502 ppem: Option<f32>,
503 ) -> Result<Option<BoundingBox<f32>>, Error> {
504 let mut bounds = charstring::ControlBoundsSink::new();
505 let mut nop_filter = charstring::NopFilterSink::new(&mut bounds);
506 let transform = self.transform(subfont, ppem);
507 let mut transformer = charstring::TransformSink::new(&mut nop_filter, transform);
508 self.evaluate_charstring(subfont, gid, coords, &mut transformer)?;
509 Ok(bounds.bounding_box().map(|b| BoundingBox {
510 x_min: b.x_min.to_f32(),
511 y_min: b.y_min.to_f32(),
512 x_max: b.x_max.to_f32(),
513 y_max: b.y_max.to_f32(),
514 }))
515 }
516
517 pub fn draw(
522 &self,
523 subfont: &Subfont,
524 gid: GlyphId,
525 coords: &[F2Dot14],
526 ppem: Option<f32>,
527 sink: &mut impl PathSink,
528 ) -> Result<Option<f32>, Error> {
529 let mut nop_filter = NopFilterSink::new(sink);
530 let transform = self.transform(subfont, ppem);
531 let mut transformer = TransformSink::new(&mut nop_filter, transform);
532 let width = self.evaluate_charstring(subfont, gid, coords, &mut transformer)?;
533 Ok(width.map(|w| transform.transform_h_metric(w).to_f32().max(0.0)))
534 }
535
536 fn blend_state(&self, vs_index: u16, coords: &'a [F2Dot14]) -> Option<BlendState<'a>> {
539 self.top_dict
540 .var_store
541 .as_ref()
542 .and_then(|store| BlendState::new(store.clone(), coords, vs_index).ok())
543 }
544}
545
546#[derive(Clone)]
548pub struct Encoding<'a> {
549 encoding: RawEncoding<'a>,
550 charset: Charset<'a>,
551}
552
553impl<'a> Encoding<'a> {
554 pub fn predefined(&self) -> Option<PredefinedEncoding> {
557 if let RawEncoding::Predefined(pre) = &self.encoding {
558 Some(*pre)
559 } else {
560 None
561 }
562 }
563
564 pub fn charset(&self) -> &Charset<'a> {
566 &self.charset
567 }
568
569 pub fn map(&self, code: u8) -> Option<GlyphId> {
571 self.encoding.map(&self.charset, code)
572 }
573}
574
575#[derive(Clone)]
577enum CffFontKind<'a> {
578 Sid {
580 strings: Index<'a>,
582 private_dict: Range<u32>,
584 },
585 Cid {
587 fd_select: Option<FdSelect<'a>>,
589 fd_array: Index<'a>,
591 },
592 Cff2 {
594 fd_select: Option<FdSelect<'a>>,
596 fd_array: Index<'a>,
598 },
599}
600
601#[derive(Copy, Clone, Default, Debug)]
613pub struct Subfont {
614 subrs_offset: u32,
615 default_width: Option<Fixed>,
616 nominal_width: Fixed,
617 matrix: Option<ScaledFontMatrix>,
618 vs_index: u16,
619}
620
621impl Subfont {
622 fn new(
623 data: &[u8],
624 range: Range<usize>,
625 blend: Option<BlendState>,
626 matrix: Option<ScaledFontMatrix>,
627 ) -> Result<Self, Error> {
628 let mut subfont = Self {
629 matrix,
630 ..Default::default()
631 };
632 let data = data.get(range.clone()).ok_or(Error::Malformed)?;
633 for entry in dict::unhinted_private_entries(data, blend).filter_map(|e| e.ok()) {
634 match entry {
635 dict::Entry::SubrsOffset(offset) => {
636 subfont.subrs_offset =
637 range.start.checked_add(offset).ok_or(Error::Malformed)? as u32;
638 }
639 dict::Entry::VariationStoreIndex(index) => subfont.vs_index = index,
640 dict::Entry::DefaultWidthX(width) => subfont.default_width = Some(width.floor()),
642 dict::Entry::NominalWidthX(width) => subfont.nominal_width = width.floor(),
643 _ => {}
644 }
645 }
646 Ok(subfont)
647 }
648
649 fn new_hinted(
650 data: &[u8],
651 range: Range<usize>,
652 blend: Option<BlendState>,
653 matrix: Option<ScaledFontMatrix>,
654 ) -> Result<(Self, HintingParams), Error> {
655 let mut subfont = Self {
656 matrix,
657 ..Default::default()
658 };
659 let mut params = HintingParams::default();
660 let data = data.get(range.clone()).ok_or(Error::Malformed)?;
661 for entry in dict::entries(data, blend).filter_map(|e| e.ok()) {
662 match entry {
663 dict::Entry::SubrsOffset(offset) => {
664 subfont.subrs_offset =
665 range.start.checked_add(offset).ok_or(Error::Malformed)? as u32;
666 }
667 dict::Entry::VariationStoreIndex(index) => subfont.vs_index = index,
668 dict::Entry::DefaultWidthX(width) => subfont.default_width = Some(width.floor()),
670 dict::Entry::NominalWidthX(width) => subfont.nominal_width = width.floor(),
671 dict::Entry::BlueValues(values) => params.blues = values,
672 dict::Entry::FamilyBlues(values) => params.family_blues = values,
673 dict::Entry::OtherBlues(values) => params.other_blues = values,
674 dict::Entry::FamilyOtherBlues(values) => params.family_other_blues = values,
675 dict::Entry::BlueScale(value) => params.blue_scale = value,
676 dict::Entry::BlueShift(value) => params.blue_shift = value,
677 dict::Entry::BlueFuzz(value) => params.blue_fuzz = value,
678 dict::Entry::LanguageGroup(group) => params.language_group = group,
679 _ => {}
680 }
681 }
682 Ok((subfont, params))
683 }
684
685 pub fn subrs_offset(&self) -> u32 {
688 self.subrs_offset
689 }
690
691 pub fn default_width(&self) -> Option<Fixed> {
695 self.default_width
696 }
697
698 pub fn nominal_width(&self) -> Fixed {
703 self.nominal_width
704 }
705
706 pub fn matrix(&self) -> Option<&ScaledFontMatrix> {
708 self.matrix.as_ref()
709 }
710
711 pub fn vs_index(&self) -> u16 {
713 self.vs_index
714 }
715}
716
717#[derive(Copy, Clone)]
719struct MaybeOffset(u32);
720
721impl MaybeOffset {
722 fn get(self) -> Option<usize> {
723 (self.0 != u32::MAX).then_some(self.0 as usize)
724 }
725}
726
727impl Default for MaybeOffset {
728 fn default() -> Self {
729 Self(u32::MAX)
730 }
731}
732
733#[derive(Clone)]
734struct TopDict<'a> {
735 charstrings: Index<'a>,
736 charset_offset: MaybeOffset,
737 encoding_offset: MaybeOffset,
738 matrix: Option<ScaledFontMatrix>,
739 var_store: Option<ItemVariationStore<'a>>,
740 kind: CffFontKind<'a>,
741}
742
743impl<'a> TopDict<'a> {
744 fn new(
745 cff_data: &'a [u8],
746 top_dict_data: &[u8],
747 strings: Index<'a>,
748 is_cff2: bool,
749 ) -> Result<Self, Error> {
750 let mut has_ros = false;
751 let mut charstrings = None;
752 let [mut charset_offset, mut encoding_offset] = if is_cff2 {
753 [MaybeOffset::default(); 2]
756 } else {
757 [MaybeOffset(0); 2]
760 };
761 let mut fd_array = None;
762 let mut fd_select = None;
763 let mut private_dict_range = 0..0;
764 let mut matrix = None;
765 let mut var_store = None;
766 for entry in dict::entries(top_dict_data, None).filter_map(|e| e.ok()) {
767 match entry {
768 dict::Entry::Ros { .. } => has_ros = true,
769 dict::Entry::CharstringsOffset(offset) => {
770 charstrings = cff_data
771 .get(offset..)
772 .and_then(|data| Index::new(data, is_cff2).ok());
773 }
774 dict::Entry::Charset(offset) => charset_offset = MaybeOffset(offset as u32),
775 dict::Entry::Encoding(offset) => encoding_offset = MaybeOffset(offset as u32),
776 dict::Entry::FdArrayOffset(offset) => {
777 fd_array = cff_data
778 .get(offset..)
779 .and_then(|data| Index::new(data, is_cff2).ok());
780 }
781 dict::Entry::FdSelectOffset(offset) => {
782 fd_select = cff_data
783 .get(offset..)
784 .and_then(|data| FdSelect::read(data.into()).ok());
785 }
786 dict::Entry::PrivateDictRange(range) => {
787 let _ = cff_data.get(range.clone()).ok_or(Error::Malformed)?;
789 private_dict_range = range;
790 }
791 dict::Entry::FontMatrix(font_matrix) => {
792 matrix = Some(font_matrix.normalize());
795 }
796 dict::Entry::VariationStoreOffset(offset) if is_cff2 => {
797 let offset = offset.checked_add(2).ok_or(Error::Malformed)?;
801 var_store = Some(ItemVariationStore::read(
802 cff_data.get(offset..).unwrap_or_default().into(),
803 )?);
804 }
805 _ => {}
806 }
807 }
808 let charstrings = charstrings.ok_or(Error::MissingResource)?;
809 let kind = if let Some(fd_array) = fd_array {
810 if is_cff2 {
811 CffFontKind::Cff2 {
812 fd_array,
813 fd_select,
814 }
815 } else {
816 CffFontKind::Cid {
817 fd_array,
818 fd_select,
819 }
820 }
821 } else {
822 if has_ros || is_cff2 {
823 return Err(Error::MissingResource);
825 }
826 CffFontKind::Sid {
827 strings,
828 private_dict: private_dict_range.start as u32..private_dict_range.end as u32,
829 }
830 };
831 Ok(Self {
832 charset_offset,
833 encoding_offset,
834 charstrings,
835 matrix,
836 kind,
837 var_store,
838 })
839 }
840}
841
842#[derive(Default)]
843struct FontDict {
844 private_dict_range: Range<usize>,
845 matrix: Option<ScaledFontMatrix>,
846}
847
848impl FontDict {
849 fn new(dict_data: &[u8]) -> Result<Self, Error> {
850 let mut range = None;
851 let mut matrix = None;
852 for entry in dict::entries(dict_data, None) {
853 match entry? {
854 dict::Entry::PrivateDictRange(dict_range) => {
855 range = Some(dict_range);
856 }
857 dict::Entry::FontMatrix(font_matrix) => {
858 matrix = Some(font_matrix);
859 }
860 _ => {}
861 }
862 }
863 Ok(Self {
864 private_dict_range: range.ok_or(Error::MissingResource)?,
865 matrix,
866 })
867 }
868}
869
870#[derive(Copy, Clone, Debug)]
875pub struct Metadata<'a> {
876 name: Option<&'a str>,
877 version: Option<&'a str>,
878 notice: Option<&'a str>,
879 copyright: Option<&'a str>,
880 full_name: Option<&'a str>,
881 family_name: Option<&'a str>,
882 weight: Option<&'a str>,
883 bbox: BoundingBox<Fixed>,
884 italic_angle: Fixed,
885 is_fixed_pitch: bool,
886 underline_position: Fixed,
887 underline_thickness: Fixed,
888}
889
890impl<'a> Metadata<'a> {
891 fn new(data: &'a [u8], top_dict_index: u16) -> Option<Self> {
892 let cff = cff::Cff::read(FontData::new(data)).ok()?;
893 let strings = cff.strings();
894 let get_str = |sid: Sid| {
895 let bytes = match sid.resolve_standard() {
896 Ok(bytes) => bytes,
897 Err(idx) => strings.get(idx)?,
898 };
899 core::str::from_utf8(bytes).ok()
900 };
901 let top_dict_data = cff.top_dicts().get(top_dict_index as usize)?;
902 let name = cff
903 .name(top_dict_index as usize)
904 .and_then(|bytes| core::str::from_utf8(bytes).ok());
905 let mut meta = Metadata {
906 name,
907 ..Default::default()
908 };
909 for entry in dict::entries(top_dict_data, None).filter_map(|e| e.ok()) {
910 match entry {
911 dict::Entry::Version(sid) => meta.version = get_str(sid),
912 dict::Entry::Notice(sid) => meta.notice = get_str(sid),
913 dict::Entry::Copyright(sid) => meta.copyright = get_str(sid),
914 dict::Entry::FullName(sid) => meta.full_name = get_str(sid),
915 dict::Entry::FamilyName(sid) => meta.family_name = get_str(sid),
916 dict::Entry::Weight(sid) => meta.weight = get_str(sid),
917 dict::Entry::FontBbox([x_min, y_min, x_max, y_max]) => {
918 meta.bbox = BoundingBox {
919 x_min,
920 x_max,
921 y_min,
922 y_max,
923 }
924 }
925 dict::Entry::ItalicAngle(angle) => meta.italic_angle = angle,
926 dict::Entry::IsFixedPitch(fixed_pitch) => meta.is_fixed_pitch = fixed_pitch,
927 dict::Entry::UnderlinePosition(pos) => meta.underline_position = pos,
928 dict::Entry::UnderlineThickness(size) => meta.underline_thickness = size,
929 _ => {}
930 }
931 }
932 Some(meta)
933 }
934
935 pub fn name(&self) -> Option<&'a str> {
937 self.name
938 }
939
940 pub fn version(&self) -> Option<&'a str> {
942 self.version
943 }
944
945 pub fn notice(&self) -> Option<&'a str> {
947 self.notice
948 }
949
950 pub fn copyright(&self) -> Option<&'a str> {
952 self.copyright
953 }
954
955 pub fn full_name(&self) -> Option<&'a str> {
957 self.full_name
958 }
959
960 pub fn family_name(&self) -> Option<&'a str> {
962 self.family_name
963 }
964
965 pub fn weight(&self) -> Option<&'a str> {
967 self.weight
968 }
969
970 pub fn italic_angle(&self) -> Fixed {
972 self.italic_angle
973 }
974
975 pub fn is_fixed_pitch(&self) -> bool {
977 self.is_fixed_pitch
978 }
979
980 pub fn underline_position(&self) -> Fixed {
982 self.underline_position
983 }
984
985 pub fn underline_thickness(&self) -> Fixed {
987 self.underline_thickness
988 }
989
990 pub fn bbox(&self) -> BoundingBox<Fixed> {
992 self.bbox
993 }
994}
995
996impl Default for Metadata<'_> {
997 fn default() -> Self {
998 Self {
999 name: None,
1000 version: None,
1001 notice: None,
1002 copyright: None,
1003 full_name: None,
1004 family_name: None,
1005 weight: None,
1006 bbox: BoundingBox::default(),
1007 italic_angle: Fixed::ZERO,
1008 is_fixed_pitch: false,
1009 underline_position: Fixed::from_i32(-100),
1010 underline_thickness: Fixed::from_i32(50),
1011 }
1012 }
1013}
1014
1015#[cfg(test)]
1016mod tests {
1017 use super::*;
1018 use crate::{
1019 ps::{hinting::Blues, transform::FontMatrix},
1020 FontData, FontRef, TableProvider,
1021 };
1022 use charstring::test_helpers::*;
1023 use font_test_data::bebuffer::BeBuffer;
1024
1025 #[test]
1026 fn read_cff_static() {
1027 let font = FontRef::new(font_test_data::NOTO_SERIF_DISPLAY_TRIMMED).unwrap();
1028 let cff =
1029 CffFontRef::new_cff(font.cff().unwrap().offset_data().as_bytes(), 0, None).unwrap();
1030 assert_eq!(cff.version(), 1);
1031 assert!(cff.var_store().is_none());
1032 let CffFontKind::Sid { private_dict, .. } = &cff.top_dict.kind else {
1033 panic!("this is an SID font");
1034 };
1035 assert!(!private_dict.is_empty());
1036 assert_eq!(cff.num_glyphs(), 5);
1037 assert_eq!(cff.num_subfonts(), 1);
1038 assert_eq!(cff.subfont_index(GlyphId::new(1)), Some(0));
1039 assert_eq!(cff.global_subrs.count(), 17);
1040 }
1041
1042 #[test]
1043 fn read_cff_metadata() {
1044 let font = FontRef::new(font_test_data::NOTO_SERIF_DISPLAY_TRIMMED).unwrap();
1045 let cff = CffFontRef::new(font.cff().unwrap().offset_data().as_bytes(), 0, None).unwrap();
1046 let meta = cff.metadata().unwrap();
1047 assert_eq!(meta.name(), Some("NotoSerifDisplay-Regular"));
1048 assert_eq!(meta.full_name(), Some("Noto Serif Display Regular"));
1049 assert_eq!(meta.family_name(), Some("Noto Serif Display"));
1050 assert_eq!(meta.weight(), None);
1051 assert_eq!(
1052 meta.bbox(),
1053 BoundingBox {
1054 x_min: Fixed::from_i32(-693),
1055 y_min: Fixed::from_i32(-470),
1056 x_max: Fixed::from_i32(2797),
1057 y_max: Fixed::from_i32(1048)
1058 }
1059 );
1060 assert_eq!(meta.italic_angle(), Fixed::ZERO);
1061 assert!(!meta.is_fixed_pitch());
1062 assert_eq!(meta.underline_position(), Fixed::from_i32(-100));
1063 assert_eq!(meta.underline_thickness(), Fixed::from_i32(50));
1064 let font = FontRef::new(font_test_data::MATERIAL_ICONS_SUBSET).unwrap();
1065 let cff = CffFontRef::new(font.cff().unwrap().offset_data().as_bytes(), 0, None).unwrap();
1066 let meta = cff.metadata().unwrap();
1067 assert_eq!(meta.name(), Some("GoogleMaterialIcons-Regular"));
1068 assert_eq!(meta.full_name(), Some("GoogleMaterialIcons-Regular"));
1069 assert_eq!(meta.family_name(), None);
1070 assert_eq!(meta.weight(), None);
1071 assert_eq!(
1072 meta.bbox(),
1073 BoundingBox {
1074 x_min: Fixed::from_i32(-1),
1075 y_min: Fixed::ZERO,
1076 x_max: Fixed::from_i32(513),
1077 y_max: Fixed::from_i32(512)
1078 }
1079 );
1080 assert_eq!(meta.italic_angle(), Fixed::ZERO);
1081 assert!(!meta.is_fixed_pitch());
1082 assert_eq!(meta.underline_position(), Fixed::from_i32(-100));
1083 assert_eq!(meta.underline_thickness(), Fixed::from_i32(50));
1084 }
1085
1086 #[test]
1087 fn read_cff2_static() {
1088 let font = FontRef::new(font_test_data::CANTARELL_VF_TRIMMED).unwrap();
1089 let cff =
1090 CffFontRef::new_cff2(font.cff2().unwrap().offset_data().as_bytes(), None).unwrap();
1091 assert_eq!(cff.version(), 2);
1092 assert!(cff.var_store().is_some());
1093 let CffFontKind::Cff2 { fd_array, .. } = &cff.top_dict.kind else {
1094 panic!("this is a CFF2 font");
1095 };
1096 assert_eq!(fd_array.count(), 1);
1097 assert_eq!(cff.num_glyphs(), 6);
1098 assert_eq!(cff.num_subfonts(), 1);
1099 assert_eq!(cff.subfont_index(GlyphId::new(1)), Some(0));
1100 assert_eq!(cff.global_subrs.count(), 0);
1101 }
1102
1103 #[test]
1104 fn read_example_cff2_table() {
1105 let cff = CffFontRef::new_cff2(font_test_data::cff2::EXAMPLE, None).unwrap();
1106 assert_eq!(cff.version(), 2);
1107 assert!(cff.var_store().is_some());
1108 let CffFontKind::Cff2 { fd_array, .. } = &cff.top_dict.kind else {
1109 panic!("this is a CFF2 font");
1110 };
1111 assert_eq!(fd_array.count(), 1);
1112 assert_eq!(cff.num_glyphs(), 2);
1113 assert_eq!(cff.num_subfonts(), 1);
1114 assert_eq!(cff.subfont_index(GlyphId::new(1)), Some(0));
1115 assert_eq!(cff.global_subrs.count(), 0);
1116 }
1117
1118 #[test]
1119 fn charset() {
1120 let font = FontRef::new(font_test_data::NOTO_SERIF_DISPLAY_TRIMMED).unwrap();
1121 let cff =
1122 CffFontRef::new_cff(font.cff().unwrap().offset_data().as_bytes(), 0, None).unwrap();
1123 let charset = cff.charset().unwrap();
1124 let glyph_names = charset
1125 .iter()
1126 .map(|(gid, sid)| {
1127 (
1128 gid.to_u32(),
1129 std::str::from_utf8(sid.resolve_standard().unwrap()).unwrap(),
1130 )
1131 })
1132 .collect::<Vec<_>>();
1133 let expected = [(0, ".notdef"), (1, "i"), (2, "j"), (3, "k"), (4, "l")];
1134 assert_eq!(glyph_names, expected)
1135 }
1136
1137 #[test]
1141 fn top_dict_ivs_offset_overflow() {
1142 let top_dict = BeBuffer::new()
1145 .push(29u8) .push(-1i32) .push(24u8) .to_vec();
1149 assert!(TopDict::new(&[], &top_dict, Index::Empty, true).is_err());
1151 }
1152
1153 #[test]
1156 fn subrs_offset_overflow() {
1157 let private_dict = BeBuffer::new()
1159 .push(0u32) .push(29u8) .push(-1i32) .push(19u8) .to_vec();
1164 assert!(Subfont::new(&private_dict, 4..private_dict.len(), None, None).is_err());
1166 }
1167
1168 #[test]
1170 fn empty_private_dict() {
1171 let font = FontRef::new(font_test_data::MATERIAL_ICONS_SUBSET).unwrap();
1172 let cff =
1173 CffFontRef::new_cff(font.cff().unwrap().offset_data().as_bytes(), 0, None).unwrap();
1174 let CffFontKind::Sid { private_dict, .. } = &cff.top_dict.kind else {
1175 panic!("this is an SID font");
1176 };
1177 assert!(private_dict.is_empty());
1178 }
1179
1180 #[test]
1182 fn capture_family_other_blues() {
1183 let private_dict_data = &font_test_data::cff2::EXAMPLE[0x4f..=0xc0];
1184 let store =
1185 ItemVariationStore::read(FontData::new(&font_test_data::cff2::EXAMPLE[18..])).unwrap();
1186 let coords = &[F2Dot14::from_f32(0.0)];
1187 let blend_state = BlendState::new(store, coords, 0).unwrap();
1188 let (_subfont, hint_params) = Subfont::new_hinted(
1189 private_dict_data,
1190 0..private_dict_data.len(),
1191 Some(blend_state),
1192 None,
1193 )
1194 .unwrap();
1195 assert_eq!(
1196 hint_params.family_other_blues,
1197 Blues::new([-249.0, -239.0].map(Fixed::from_f64).into_iter())
1198 )
1199 }
1200
1201 #[test]
1202 fn subfont_cff() {
1203 let font = FontRef::new(font_test_data::NOTO_SERIF_DISPLAY_TRIMMED).unwrap();
1204 let cff =
1205 CffFontRef::new_cff(font.cff().unwrap().offset_data().as_bytes(), 0, None).unwrap();
1206 let subfont = cff.subfont(0, &[]).unwrap();
1207 assert_eq!(subfont.default_width, None);
1208 assert_eq!(subfont.nominal_width, Fixed::from_i32(598));
1209 assert_eq!(subfont.vs_index, 0);
1210 assert_eq!(subfont.matrix, None);
1211 }
1212
1213 fn make_blues<const N: usize>(values: [i32; N]) -> Blues {
1214 Blues::new(values.map(Fixed::from_i32).into_iter())
1215 }
1216
1217 #[test]
1218 fn hinted_subfont_cff() {
1219 let font = FontRef::new(font_test_data::NOTO_SERIF_DISPLAY_TRIMMED).unwrap();
1220 let cff =
1221 CffFontRef::new_cff(font.cff().unwrap().offset_data().as_bytes(), 0, None).unwrap();
1222 let (subfont, hinting) = cff.subfont_hinted(0, &[]).unwrap();
1223 assert_eq!(subfont.default_width, None);
1224 assert_eq!(subfont.nominal_width, Fixed::from_i32(598));
1225 assert_eq!(subfont.vs_index, 0);
1226 assert_eq!(subfont.matrix, None);
1227 let expected_hinting = HintingParams {
1228 blues: make_blues([-15, 0, 536, 547, 571, 582, 714, 726, 760, 772]),
1229 family_blues: Blues::default(),
1230 other_blues: make_blues([-255, -240]),
1231 family_other_blues: Blues::default(),
1232 blue_scale: Fixed::from_f64(0.0500030517578125),
1233 blue_shift: Fixed::from_f64(7.0),
1234 blue_fuzz: Fixed::ZERO,
1235 language_group: 0,
1236 };
1237 assert_eq!(hinting, expected_hinting);
1238 }
1239
1240 #[test]
1241 fn subfont_cff2() {
1242 let font = FontRef::new(font_test_data::CANTARELL_VF_TRIMMED).unwrap();
1243 let cff =
1244 CffFontRef::new_cff2(font.cff2().unwrap().offset_data().as_bytes(), None).unwrap();
1245 let subfont = cff.subfont(0, &[]).unwrap();
1246 assert_eq!(subfont.default_width, None);
1247 assert_eq!(subfont.nominal_width, Fixed::ZERO);
1248 assert_eq!(subfont.vs_index, 0);
1249 assert_eq!(subfont.matrix, None);
1250 }
1251
1252 #[test]
1253 fn hinted_subfont_cff2() {
1254 let font = FontRef::new(font_test_data::CANTARELL_VF_TRIMMED).unwrap();
1255 let cff =
1256 CffFontRef::new_cff2(font.cff2().unwrap().offset_data().as_bytes(), None).unwrap();
1257 let (subfont, hinting) = cff.subfont_hinted(0, &[]).unwrap();
1258 assert_eq!(subfont.default_width, None);
1259 assert_eq!(subfont.nominal_width, Fixed::ZERO);
1260 assert_eq!(subfont.vs_index, 0);
1261 assert_eq!(subfont.matrix, None);
1262 let expected_hinting = HintingParams {
1263 blues: make_blues([-10, 0, 482, 492, 694, 704, 739, 749]),
1264 family_blues: Blues::default(),
1265 other_blues: make_blues([-227, -217]),
1266 family_other_blues: Blues::default(),
1267 blue_scale: Fixed::from_f64(0.0625),
1268 blue_shift: Fixed::from_f64(7.0),
1269 blue_fuzz: Fixed::ONE,
1270 language_group: 0,
1271 };
1272 assert_eq!(hinting, expected_hinting);
1273 }
1274
1275 #[test]
1276 fn subfont_matrix() {
1277 let font = FontRef::new(font_test_data::MATERIAL_ICONS_SUBSET_MATRIX).unwrap();
1278 let cff =
1279 CffFontRef::new_cff(font.cff().unwrap().offset_data().as_bytes(), 0, None).unwrap();
1280 let subfont = cff.subfont(0, &[]).unwrap();
1281 assert_eq!(subfont.default_width, None);
1282 assert_eq!(subfont.nominal_width, Fixed::ZERO);
1283 assert_eq!(subfont.vs_index, 0);
1284 let expected_matrix = FontMatrix::from_elements([
1285 Fixed::from_i32(5),
1286 Fixed::ZERO,
1287 Fixed::ZERO,
1288 Fixed::from_i32(5),
1289 Fixed::ZERO,
1290 Fixed::ZERO,
1291 ]);
1292 let expected_scale = 10;
1293 assert_eq!(
1294 subfont.matrix,
1295 Some(ScaledFontMatrix {
1296 matrix: expected_matrix,
1297 scale: expected_scale
1298 })
1299 );
1300 }
1301
1302 #[test]
1303 fn eval_charstring_cff() {
1304 let font = FontRef::new(font_test_data::NOTO_SERIF_DISPLAY_TRIMMED).unwrap();
1305 let cff =
1306 CffFontRef::new_cff(font.cff().unwrap().offset_data().as_bytes(), 0, None).unwrap();
1307 let mut sink = CharstringCommandCounter::default();
1308 let subfont = cff.subfont(0, &[]).unwrap();
1309 cff.evaluate_charstring(&subfont, GlyphId::new(2), &[], &mut sink)
1310 .unwrap();
1311 assert_eq!(sink.0, 18);
1314 }
1315
1316 #[test]
1317 fn eval_charstring_cff2() {
1318 let font = FontRef::new(font_test_data::CANTARELL_VF_TRIMMED).unwrap();
1319 let cff =
1320 CffFontRef::new_cff2(font.cff2().unwrap().offset_data().as_bytes(), None).unwrap();
1321 let mut sink = CharstringCommandCounter::default();
1322 let subfont = cff.subfont(0, &[]).unwrap();
1323 cff.evaluate_charstring(&subfont, GlyphId::new(2), &[], &mut sink)
1324 .unwrap();
1325 assert_eq!(sink.0, 11);
1328 }
1329
1330 #[test]
1331 fn select_version() {
1332 assert_eq!(
1334 CffFontRef::new(
1335 FontRef::new(font_test_data::CANTARELL_VF_TRIMMED)
1336 .unwrap()
1337 .cff2()
1338 .unwrap()
1339 .offset_data()
1340 .as_bytes(),
1341 0,
1342 None
1343 )
1344 .unwrap()
1345 .version(),
1346 2
1347 );
1348 assert_eq!(
1350 CffFontRef::new(
1351 FontRef::new(font_test_data::MATERIAL_ICONS_SUBSET_MATRIX)
1352 .unwrap()
1353 .cff()
1354 .unwrap()
1355 .offset_data()
1356 .as_bytes(),
1357 0,
1358 None
1359 )
1360 .unwrap()
1361 .version(),
1362 1
1363 );
1364 assert!(CffFontRef::new(&[0, 1, 4, 5], 0, None).is_err());
1366 assert!(CffFontRef::new(&[1, 1, 4, 5], 0, None).is_err());
1368 assert!(CffFontRef::new(&[2, 1, 4, 5], 0, None).is_err());
1370 }
1371
1372 #[test]
1373 fn transform() {
1374 let font = FontRef::new(font_test_data::MATERIAL_ICONS_SUBSET_MATRIX).unwrap();
1376 let cff =
1378 CffFontRef::new(font.cff().unwrap().offset_data().as_bytes(), 0, Some(512)).unwrap();
1379 let subfont = cff.subfont(0, &[]).unwrap();
1380 let expected_matrix = [65536, 0, 5604, 65536, 0, 0].map(Fixed::from_bits);
1382 let transform = cff.transform(&subfont, None);
1384 assert_eq!(transform.matrix.elements(), expected_matrix);
1385 assert_eq!(transform.scale, Some(Fixed::from_bits(32 << 16)));
1386 let transform = cff.transform(&subfont, Some(16.0));
1388 assert_eq!(transform.matrix.elements(), expected_matrix);
1389 assert_eq!(transform.scale, Some(Fixed::from_bits(1 << 16)));
1390 }
1391
1392 #[test]
1393 fn cff_encoding() {
1394 let font = FontRef::new(font_test_data::NOTO_SERIF_DISPLAY_TRIMMED).unwrap();
1395 let cff = CffFontRef::new(font.cff().unwrap().offset_data().as_bytes(), 0, None).unwrap();
1396 let encoding = cff.encoding().unwrap();
1397 assert_eq!(encoding.predefined(), Some(PredefinedEncoding::Standard));
1398 }
1399
1400 #[test]
1401 fn cff2_lacks_encoding() {
1402 let font = FontRef::new(font_test_data::CANTARELL_VF_TRIMMED).unwrap();
1403 let cff = CffFontRef::new(font.cff2().unwrap().offset_data().as_bytes(), 0, None).unwrap();
1404 assert!(cff.encoding().is_none());
1405 }
1406}
1407
1408#[cfg(test)]
1409mod width_only_tests {
1410 use super::*;
1411 use crate::{model::glyph::outline::NullSink, FontRef, TableProvider};
1412
1413 const FONTS: [&[u8]; 3] = [
1414 font_test_data::NOTO_SERIF_DISPLAY_TRIMMED,
1415 font_test_data::ift::CFF_FONT,
1416 font_test_data::MATERIAL_ICONS_SUBSET_MATRIX,
1419 ];
1420
1421 fn for_each_glyph(data: &[u8], mut check: impl FnMut(&CffFontRef, &Subfont, GlyphId)) {
1423 let font = FontRef::new(data).unwrap();
1424 let cff =
1425 CffFontRef::new_cff(font.cff().unwrap().offset_data().as_bytes(), 0, None).unwrap();
1426 let num_glyphs = font.maxp().unwrap().num_glyphs() as u32;
1427 assert!(num_glyphs > 1);
1428 for gid in (0..num_glyphs).map(GlyphId::new) {
1429 let index = cff.subfont_index(gid).unwrap_or(0);
1430 let subfont = cff.subfont(index, &[]).unwrap();
1431 check(&cff, &subfont, gid);
1432 }
1433 }
1434
1435 #[test]
1436 fn the_quick_width_is_what_a_full_run_reports() {
1437 let mut mapped = 0;
1438 for data in FONTS {
1439 let mut stated = 0;
1440 for_each_glyph(data, |cff, subfont, gid| {
1441 let transform = cff.transform(subfont, None);
1445 let full = cff
1446 .evaluate_charstring(subfont, gid, &[], &mut charstring::NullSink)
1447 .unwrap();
1448 let quick = cff.evaluate_width(subfont, gid, &[]).unwrap();
1449 assert_eq!(
1450 full.map(|width| transform.transform_h_metric(width)),
1451 quick,
1452 "glyph {gid}"
1453 );
1454 stated += full.is_some() as u32;
1455 if let (Some(full), Some(quick)) = (full, quick) {
1456 mapped += (full != quick) as u32;
1457 }
1458 });
1459 assert!(stated > 0, "no glyph reported a width");
1461 }
1462 assert!(mapped > 0, "no width was moved by a matrix");
1465 }
1466
1467 #[test]
1468 fn the_quick_advance_is_what_drawing_reports() {
1469 for data in FONTS {
1472 for ppem in [None, Some(16.0), Some(72.0)] {
1473 for_each_glyph(data, |cff, subfont, gid| {
1474 let drawn = cff.draw(subfont, gid, &[], ppem, &mut NullSink).unwrap();
1475 let quick = cff.advance(subfont, gid, &[], ppem).unwrap();
1476 assert_eq!(drawn, quick, "glyph {gid} at {ppem:?}");
1477 });
1478 }
1479 }
1480 }
1481}
1482
1483#[cfg(test)]
1484mod extents_tests {
1485 use super::*;
1486 use crate::{model::glyph::outline::PathSink, FontRef, TableProvider};
1487
1488 const SHEARED: &[u8] = font_test_data::MATERIAL_ICONS_SUBSET_MATRIX;
1491
1492 #[derive(Default)]
1493 struct BoundsPen(Option<[f32; 4]>);
1494
1495 impl BoundsPen {
1496 fn add(&mut self, x: f32, y: f32) {
1497 self.0 = Some(match self.0 {
1498 Some([a, b, c, d]) => [a.min(x), b.min(y), c.max(x), d.max(y)],
1499 None => [x, y, x, y],
1500 });
1501 }
1502 }
1503
1504 impl PathSink for BoundsPen {
1505 fn move_to(&mut self, x: f32, y: f32) {
1506 self.add(x, y);
1507 }
1508 fn line_to(&mut self, x: f32, y: f32) {
1509 self.add(x, y);
1510 }
1511 fn quad_to(&mut self, cx: f32, cy: f32, x: f32, y: f32) {
1512 self.add(cx, cy);
1513 self.add(x, y);
1514 }
1515 fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {
1516 self.add(cx0, cy0);
1517 self.add(cx1, cy1);
1518 self.add(x, y);
1519 }
1520 fn close(&mut self) {}
1521 }
1522
1523 fn corners(b: BoundingBox<f32>) -> [f32; 4] {
1524 [b.x_min, b.y_min, b.x_max, b.y_max]
1525 }
1526
1527 fn cff_of(data: &[u8]) -> CffFontRef<'_> {
1528 let font = FontRef::new(data).unwrap();
1529 CffFontRef::new_cff(font.cff().unwrap().offset_data().as_bytes(), 0, None).unwrap()
1530 }
1531
1532 fn each_glyph(data: &[u8], mut f: impl FnMut(&CffFontRef, &Subfont, GlyphId)) {
1533 let cff = cff_of(data);
1534 for gid in (0..cff.num_glyphs()).map(GlyphId::new) {
1535 let index = cff.subfont_index(gid).unwrap_or(0);
1536 let subfont = cff.subfont(index, &[]).unwrap();
1537 f(&cff, &subfont, gid);
1538 }
1539 }
1540
1541 #[test]
1542 fn the_extents_are_the_box_drawing_stays_within() {
1543 for data in [
1544 font_test_data::NOTO_SERIF_DISPLAY_TRIMMED,
1545 font_test_data::ift::CFF_FONT,
1546 SHEARED,
1547 ] {
1548 for ppem in [None, Some(16.0)] {
1549 let mut drew = 0;
1550 each_glyph(data, |cff, subfont, gid| {
1551 let mut pen = BoundsPen::default();
1552 cff.draw(subfont, gid, &[], ppem, &mut pen).unwrap();
1553 let measured = cff.extents(subfont, gid, &[], ppem).unwrap();
1554 assert_eq!(measured.map(corners), pen.0, "glyph {gid} at {ppem:?}");
1555 drew += pen.0.is_some() as u32;
1556 });
1557 assert!(drew > 0, "nothing drew, so this proves nothing");
1558 }
1559 }
1560 }
1561
1562 #[test]
1563 fn a_sheared_matrix_measures_smaller_than_a_box_turned_afterwards() {
1564 let mut tighter = 0;
1568 each_glyph(SHEARED, |cff, subfont, gid| {
1569 let mut before = charstring::ControlBoundsSink::new();
1573 let mut filter = charstring::NopFilterSink::new(&mut before);
1574 cff.evaluate_charstring(subfont, gid, &[], &mut filter)
1575 .unwrap();
1576 let Some(plain) = before.bounding_box() else {
1577 return;
1578 };
1579 let mut turned = charstring::ControlBoundsSink::new();
1580 let transform = cff.transform(subfont, None);
1581 let mut sink = charstring::TransformSink::new(&mut turned, transform);
1582 for (x, y) in [
1583 (plain.x_min, plain.y_min),
1584 (plain.x_min, plain.y_max),
1585 (plain.x_max, plain.y_min),
1586 (plain.x_max, plain.y_max),
1587 ] {
1588 sink.move_to(x, y);
1589 }
1590 let turned = turned.bounding_box().unwrap();
1591 let measured = cff.extents(subfont, gid, &[], None).unwrap().unwrap();
1592 assert!(measured.x_min >= turned.x_min.to_f32());
1594 assert!(measured.x_max <= turned.x_max.to_f32());
1595 if measured.x_min > turned.x_min.to_f32() || measured.x_max < turned.x_max.to_f32() {
1596 tighter += 1;
1597 }
1598 });
1599 assert!(
1600 tighter > 0,
1601 "no glyph measured tighter, so the shear went unnoticed"
1602 );
1603 }
1604
1605 #[test]
1606 fn a_location_moves_a_cff2_box_as_it_moves_the_drawing() {
1607 let data = font_test_data::ift::CFF2_FONT;
1611 let font = FontRef::new(data).unwrap();
1612 let cff =
1613 CffFontRef::new_cff2(font.cff2().unwrap().offset_data().as_bytes(), None).unwrap();
1614 let axes = font.fvar().unwrap().axis_count() as usize;
1615 let mut at_default: Vec<Option<[f32; 4]>> = Vec::new();
1616 let mut moved = 0;
1617 for coord in [0.0f32, -1.0, 1.0] {
1618 let coords: Vec<_> = (0..axes).map(|_| F2Dot14::from_f32(coord)).collect();
1619 for (i, gid) in (0..cff.num_glyphs()).map(GlyphId::new).enumerate() {
1620 let index = cff.subfont_index(gid).unwrap_or(0);
1621 let subfont = cff.subfont(index, &coords).unwrap();
1622 let measured = cff
1623 .extents(&subfont, gid, &coords, None)
1624 .unwrap()
1625 .map(corners);
1626 let mut pen = BoundsPen::default();
1627 cff.draw(&subfont, gid, &coords, None, &mut pen).unwrap();
1628 assert_eq!(measured, pen.0, "glyph {gid} at {coord}");
1629 if coord == 0.0 {
1630 at_default.push(measured);
1631 } else if at_default[i] != measured {
1632 moved += 1;
1633 }
1634 }
1635 }
1636 assert!(moved > 0, "no box moved, so the location went unread");
1637 }
1638}