1use alloc::vec::Vec;
40
41use font_model::{Font, FontMetrics, GlyphId, Outline};
42
43use crate::affine::Affine2D;
44use crate::error::ShapeError;
45use crate::path::{Path2D, PathBuilder};
46use crate::raster::{fill_path, mask_coverage, FillRule, MAX_MASK_ELEMENTS};
47
48pub const PIXEL_FP_BITS: u32 = 6;
50
51pub const PIXEL: i32 = 1 << PIXEL_FP_BITS;
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
60pub enum Hinting {
61 #[default]
65 None,
66 GridFit,
73}
74
75impl Hinting {
76 #[must_use]
78 pub const fn toggled(self) -> Hinting {
79 match self {
80 Hinting::None => Hinting::GridFit,
81 Hinting::GridFit => Hinting::None,
82 }
83 }
84
85 #[must_use]
87 pub const fn is_grid_fit(self) -> bool {
88 matches!(self, Hinting::GridFit)
89 }
90}
91
92#[must_use]
106pub fn to_fixed(value: f32) -> i32 {
107 if value.is_nan() {
108 return 0;
109 }
110 let scaled = libm::roundf(value * PIXEL as f32);
111 if scaled >= i32::MAX as f32 {
114 return i32::MAX;
115 }
116 if scaled <= i32::MIN as f32 {
117 return i32::MIN;
118 }
119 scaled as i32
120}
121
122#[must_use]
128pub fn to_26_6(value: f32) -> i32 {
129 to_fixed(value / PIXEL as f32)
130}
131
132#[must_use]
142pub fn from_fixed(value: i32) -> f32 {
143 value as f32 / PIXEL as f32
144}
145
146#[must_use]
156pub const fn grid_fit(value: i32) -> i32 {
157 let snapped = if value >= 0 {
158 (value + (PIXEL / 2)) / PIXEL
159 } else {
160 -((-value + (PIXEL / 2)) / PIXEL)
161 };
162 snapped * PIXEL
163}
164
165#[allow(clippy::result_large_err)]
181pub fn fixed_scale(size_px: f32, units_per_em: u16) -> Result<f32, ShapeError> {
182 if units_per_em == 0 {
183 return Err(ShapeError::DegenerateUnitsPerEm);
184 }
185 if !size_px.is_finite() || size_px <= 0.0 {
186 return Err(ShapeError::InvalidScale { scale: size_px });
187 }
188 Ok(size_px * PIXEL as f32 / f32::from(units_per_em))
189}
190
191#[derive(Debug, Clone, PartialEq, Eq, Default)]
216pub struct GlyphBitmap {
217 width: u32,
218 height: u32,
219 left: i32,
220 top: i32,
221 coverage: Vec<u8>,
222}
223
224impl GlyphBitmap {
225 #[must_use]
227 pub const fn empty() -> Self {
228 GlyphBitmap {
229 width: 0,
230 height: 0,
231 left: 0,
232 top: 0,
233 coverage: Vec::new(),
234 }
235 }
236
237 #[must_use]
239 pub const fn new(width: u32, height: u32, left: i32, top: i32, coverage: Vec<u8>) -> Self {
240 GlyphBitmap {
241 width,
242 height,
243 left,
244 top,
245 coverage,
246 }
247 }
248
249 #[must_use]
251 pub const fn width(&self) -> u32 {
252 self.width
253 }
254
255 #[must_use]
257 pub const fn height(&self) -> u32 {
258 self.height
259 }
260
261 #[must_use]
264 pub const fn left(&self) -> i32 {
265 self.left
266 }
267
268 #[must_use]
270 pub const fn top(&self) -> i32 {
271 self.top
272 }
273
274 #[must_use]
276 pub fn coverage(&self) -> &[u8] {
277 &self.coverage
278 }
279
280 #[must_use]
282 pub fn into_coverage(self) -> Vec<u8> {
283 self.coverage
284 }
285
286 #[must_use]
289 pub fn is_empty(&self) -> bool {
290 self.width == 0 || self.height == 0 || self.coverage.is_empty()
291 }
292
293 #[must_use]
298 pub fn ink(&self) -> f64 {
299 mask_coverage(&self.coverage) / 255.0
300 }
301
302 #[must_use]
314 pub fn coverage_at(&self, x: u32, y: u32) -> u8 {
315 if x >= self.width || y >= self.height {
316 return 0;
317 }
318 let idx = y as usize * self.width as usize + x as usize;
319 self.coverage.get(idx).copied().unwrap_or(0)
320 }
321
322 #[must_use]
324 pub fn row(&self, y: u32) -> &[u8] {
325 if y >= self.height {
326 return &[];
327 }
328 let start = y as usize * self.width as usize;
329 let end = start + self.width as usize;
330 self.coverage.get(start..end).unwrap_or(&[])
331 }
332
333 #[must_use]
348 pub fn ink_bounds(&self) -> Option<(u32, u32, u32, u32)> {
349 if self.is_empty() {
350 return None;
351 }
352 let mut x0 = u32::MAX;
353 let mut y0 = u32::MAX;
354 let mut x1 = 0u32;
355 let mut y1 = 0u32;
356 let mut any = false;
357 for y in 0..self.height {
358 for (x, &v) in self.row(y).iter().enumerate() {
359 if v > 0 {
360 let x = x as u32;
361 x0 = x0.min(x);
362 x1 = x1.max(x);
363 y0 = y0.min(y);
364 y1 = y1.max(y);
365 any = true;
366 }
367 }
368 }
369 if any {
370 Some((x0, y0, x1 - x0 + 1, y1 - y0 + 1))
371 } else {
372 None
373 }
374 }
375
376 #[must_use]
378 pub const fn translated(mut self, dx: i32, dy: i32) -> Self {
379 self.left += dx;
380 self.top += dy;
381 self
382 }
383}
384
385#[allow(clippy::result_large_err)]
415pub fn glyph_path_from_outline(
416 outline: &Outline,
417 units_per_em: u16,
418 size_px: f32,
419 hinting: Hinting,
420) -> Result<Path2D, ShapeError> {
421 let scale = fixed_scale(size_px, units_per_em)?;
422 let mut b = PathBuilder::new();
423 for contour in outline.contours() {
424 let mut started = false;
425 for cmd in contour.commands() {
426 let project = |x: f32, y: f32| -> (f32, f32) {
427 let fx = to_26_6(x * scale);
432 let fy = to_26_6(-y * scale);
433 let (fx, fy) = if hinting.is_grid_fit() {
434 (grid_fit(fx), grid_fit(fy))
435 } else {
436 (fx, fy)
437 };
438 (from_fixed(fx), from_fixed(fy))
439 };
440 match *cmd {
441 font_model::Command::MoveTo(x, y) => {
442 let (x, y) = project(x, y);
443 b.move_to(x, y);
444 started = true;
445 }
446 font_model::Command::LineTo(x, y) => {
447 let (x, y) = project(x, y);
448 if started {
449 b.line_to(x, y);
450 }
451 }
452 font_model::Command::QuadTo(cx, cy, x, y) => {
453 let (cx, cy) = project(cx, cy);
454 let (x, y) = project(x, y);
455 if started {
456 b.quad_to(cx, cy, x, y);
457 }
458 }
459 font_model::Command::CubicTo(c1x, c1y, c2x, c2y, x, y) => {
460 let (c1x, c1y) = project(c1x, c1y);
461 let (c2x, c2y) = project(c2x, c2y);
462 let (x, y) = project(x, y);
463 if started {
464 b.cubic_to(c1x, c1y, c2x, c2y, x, y);
465 }
466 }
467 font_model::Command::Close => {
468 if started {
469 b.close();
470 }
471 started = false;
472 }
473 }
474 }
475 }
476 Ok(b.build())
477}
478
479#[allow(clippy::result_large_err)]
511pub fn glyph_path(
512 font: &Font,
513 glyph: GlyphId,
514 size_px: f32,
515 hinting: Hinting,
516) -> Result<Path2D, ShapeError> {
517 let g = font.glyph(glyph).ok_or(ShapeError::UnknownGlyph {
518 glyph: glyph.to_u32(),
519 glyph_count: font.glyph_count(),
520 })?;
521 glyph_path_from_outline(g.outline(), font.units_per_em(), size_px, hinting)
522}
523
524#[allow(clippy::result_large_err)]
536pub fn rasterize_outline(
537 outline: &Outline,
538 units_per_em: u16,
539 size_px: f32,
540 hinting: Hinting,
541) -> Result<GlyphBitmap, ShapeError> {
542 let _ = fixed_scale(size_px, units_per_em)?;
545 if outline.contours().is_empty() {
546 return Ok(GlyphBitmap::empty());
547 }
548 let path = glyph_path_from_outline(outline, units_per_em, size_px, hinting)?;
549 let Some(bbox) = path.bbox() else {
550 return Ok(GlyphBitmap::empty());
551 };
552 if bbox.is_empty()
556 || !bbox.min_x.is_finite()
557 || !bbox.min_y.is_finite()
558 || !bbox.max_x.is_finite()
559 || !bbox.max_y.is_finite()
560 {
561 return Ok(GlyphBitmap::empty());
562 }
563 let left = floor_i32(bbox.min_x);
564 let right = ceil_i32(bbox.max_x);
565 let top = ceil_i32(-bbox.min_y);
567 let bottom = floor_i32(-bbox.max_y);
569 let width_i = right - left;
570 let height_i = top - bottom;
571 if width_i <= 0 || height_i <= 0 {
572 return Ok(GlyphBitmap::empty());
573 }
574 let (Ok(width_u), Ok(height_u)) = (u32::try_from(width_i), u32::try_from(height_i)) else {
575 return Ok(GlyphBitmap::empty());
576 };
577 let pixels = (width_u as usize).saturating_mul(height_u as usize);
578 if pixels > MAX_MASK_ELEMENTS {
579 return Err(ShapeError::RasterTooLarge {
580 pixels,
581 limit: MAX_MASK_ELEMENTS,
582 });
583 }
584 let placed = path.transformed(&Affine2D::translate(-(left as f32), top as f32));
587 let mask = fill_path(&placed, FillRule::NonZero, width_u, height_u)?;
588 Ok(GlyphBitmap::new(width_u, height_u, left, top, mask))
589}
590
591#[allow(clippy::result_large_err)]
629pub fn rasterize_glyph(
630 font: &Font,
631 glyph: GlyphId,
632 size_px: f32,
633 hinting: Hinting,
634) -> Result<GlyphBitmap, ShapeError> {
635 let g = font.glyph(glyph).ok_or(ShapeError::UnknownGlyph {
636 glyph: glyph.to_u32(),
637 glyph_count: font.glyph_count(),
638 })?;
639 rasterize_outline(g.outline(), font.units_per_em(), size_px, hinting)
640}
641
642#[must_use]
644pub fn em_size_px(size_px: f32) -> f32 {
645 if size_px.is_finite() && size_px > 0.0 {
646 size_px
647 } else {
648 0.0
649 }
650}
651
652#[allow(clippy::result_large_err)]
671pub fn scaled_metrics(font: &Font, size_px: f32) -> Result<DeviceMetrics, ShapeError> {
672 if !size_px.is_finite() || size_px <= 0.0 {
673 return Err(ShapeError::InvalidScale { scale: size_px });
674 }
675 let scale = size_px / f32::from(font.units_per_em().max(1));
676 Ok(DeviceMetrics::from_font(font.metrics(), scale))
677}
678
679#[derive(Debug, Clone, Copy, PartialEq)]
681pub struct DeviceMetrics {
682 pub ascent: f32,
684 pub descent: f32,
686 pub line_gap: f32,
688 pub line_height: f32,
691}
692
693impl DeviceMetrics {
694 #[must_use]
696 pub fn from_font(m: &FontMetrics, scale: f32) -> Self {
697 let ascent = f32::from(m.ascender) * scale;
698 let descent = -f32::from(m.descender) * scale;
699 let line_gap = f32::from(m.line_gap) * scale;
700 DeviceMetrics {
701 ascent,
702 descent,
703 line_gap,
704 line_height: ascent + descent + line_gap,
705 }
706 }
707}
708
709fn floor_i32(v: f32) -> i32 {
711 if v.is_nan() {
712 return 0;
713 }
714 if v <= i32::MIN as f32 {
715 return i32::MIN;
716 }
717 if v >= i32::MAX as f32 {
718 return i32::MAX;
719 }
720 libm::floorf(v) as i32
721}
722
723fn ceil_i32(v: f32) -> i32 {
725 if v.is_nan() {
726 return 0;
727 }
728 if v <= i32::MIN as f32 {
729 return i32::MIN;
730 }
731 if v >= i32::MAX as f32 {
732 return i32::MAX;
733 }
734 libm::ceilf(v) as i32
735}
736
737#[cfg(test)]
738mod tests {
739 #![allow(
740 clippy::unwrap_used,
741 clippy::expect_used,
742 clippy::panic,
743 clippy::indexing_slicing,
744 clippy::float_cmp
745 )]
746 use super::{
747 em_size_px, fixed_scale, from_fixed, glyph_path, glyph_path_from_outline, grid_fit,
748 rasterize_glyph, rasterize_outline, scaled_metrics, to_fixed, DeviceMetrics, GlyphBitmap,
749 Hinting, PIXEL,
750 };
751 use crate::error::ShapeError;
752 use alloc::string::ToString;
753 use alloc::vec;
754 use alloc::vec::Vec;
755 use font_model::{Command, Font, Glyph, GlyphId, Outline, Path};
756
757 fn close(a: f32, b: f32) -> bool {
761 (a - b).abs() < 1e-4
762 }
763
764 fn square(x0: f32, y0: f32, x1: f32, y1: f32) -> Outline {
766 let mut outline = Outline::new();
767 let mut p = Path::starting_at(x0, y0);
768 p.line_to(x1, y0);
769 p.line_to(x1, y1);
770 p.line_to(x0, y1);
771 p.close();
772 outline.push_contour(p);
773 outline
774 }
775
776 #[test]
777 fn fixed_point_round_trips() {
778 assert_eq!(PIXEL, 64);
779 for v in [0.0f32, 0.5, 1.0, 1.25, -0.75, 100.0, 1.0 / 64.0] {
780 assert!(close(from_fixed(to_fixed(v)), v), "{v}");
781 }
782 assert_eq!(to_fixed(1.0), PIXEL);
783 assert_eq!(from_fixed(PIXEL), 1.0);
784 assert_eq!(to_fixed(0.25), 16);
786 assert!(close(from_fixed(to_fixed(-0.007_812_5)), -0.015_625));
789 }
790
791 #[test]
792 fn fixed_point_saturates_instead_of_wrapping() {
793 assert_eq!(to_fixed(f32::NAN), 0);
794 assert_eq!(to_fixed(f32::INFINITY), i32::MAX);
795 assert_eq!(to_fixed(f32::NEG_INFINITY), i32::MIN);
796 assert_eq!(to_fixed(1e18), i32::MAX);
797 assert_eq!(to_fixed(-1e18), i32::MIN);
798 assert!(from_fixed(i32::MAX).is_finite());
799 assert!(from_fixed(i32::MIN).is_finite());
800 }
801
802 #[test]
803 fn grid_fit_snaps_to_the_pixel_grid() {
804 assert_eq!(grid_fit(0), 0);
805 assert_eq!(grid_fit(32), 64);
806 assert_eq!(grid_fit(-32), -64);
807 assert_eq!(grid_fit(100), 128);
808 assert_eq!(grid_fit(31), 0);
809 assert_eq!(grid_fit(-31), 0);
810 assert_eq!(grid_fit(95), 64);
811 for v in [-500, -64, -1, 0, 1, 33, 200] {
813 assert_eq!(grid_fit(grid_fit(v)), grid_fit(v), "{v}");
814 }
815 }
816
817 #[test]
818 fn fixed_scale_is_size_times_sixty_four_over_upem() {
819 assert!(close(fixed_scale(16.0, 1000).expect("scale"), 1.024));
820 assert!(close(fixed_scale(24.0, 2048).expect("scale"), 0.75));
821 let a = fixed_scale(12.0, 1000).expect("scale");
823 let b = fixed_scale(24.0, 1000).expect("scale");
824 assert!(close(a, b * 0.5));
825 }
826
827 #[test]
828 fn fixed_scale_rejects_degenerate_inputs() {
829 assert_eq!(
830 fixed_scale(16.0, 0).unwrap_err(),
831 ShapeError::DegenerateUnitsPerEm
832 );
833 for bad in [0.0, -1.0, f32::NAN, f32::INFINITY] {
834 assert!(
835 matches!(fixed_scale(bad, 1000), Err(ShapeError::InvalidScale { .. })),
836 "{bad}"
837 );
838 }
839 }
840
841 #[test]
842 fn glyph_path_flips_y_and_scales() {
843 let outline = square(0.0, 0.0, 1000.0, 1000.0);
846 let path = glyph_path_from_outline(&outline, 1000, 100.0, Hinting::None).expect("path");
847 let b = path.bbox().expect("bbox");
848 assert_eq!(b.min_x, 0.0);
849 assert_eq!(b.min_y, -100.0);
850 assert_eq!(b.max_x, 100.0);
851 assert_eq!(b.max_y, 0.0);
852 }
853
854 #[test]
855 fn glyph_path_carries_curves_through() {
856 let mut outline = Outline::new();
857 let mut p = Path::starting_at(0.0, 0.0);
858 p.cubic_to(500.0, 500.0, 1000.0, 500.0, 1000.0, 0.0);
859 p.close();
860 outline.push_contour(p);
861 let path = glyph_path_from_outline(&outline, 1000, 100.0, Hinting::None).expect("path");
862 assert!(path
864 .commands()
865 .iter()
866 .any(|c| matches!(c, crate::PathCommand::CubicTo(..))));
867 let b = path.bbox().expect("bbox");
868 assert!(b.min_y < -10.0, "the curve bows up: {b:?}");
869 }
870
871 #[test]
872 fn grid_fit_snaps_the_whole_outline_to_pixels() {
873 let outline = square(0.0, 0.0, 1000.0, 1000.0);
874 let path = glyph_path_from_outline(&outline, 1000, 7.3, Hinting::GridFit).expect("path");
875 for cmd in path.commands() {
876 if let Some((x, y)) = cmd.end_point() {
877 assert!(close(x, libm::roundf(x)), "x {x} is not a whole pixel");
878 assert!(close(y, libm::roundf(y)), "y {y} is not a whole pixel");
879 }
880 }
881 let raw = glyph_path_from_outline(&outline, 1000, 7.3, Hinting::None).expect("path");
883 let snapped = path.bbox().expect("bbox");
884 let plain = raw.bbox().expect("bbox");
885 assert!((plain.width() - 7.3).abs() < 0.02, "{plain:?}");
888 assert!((plain.height() - 7.3).abs() < 0.02, "{plain:?}");
889 assert_eq!(snapped.width(), 7.0, "grid fit rounds 7.3 down to 7");
890 assert_eq!(snapped.height(), 7.0, "{snapped:?}");
891 }
892
893 #[test]
894 fn grid_fit_can_change_the_measured_size_by_a_pixel() {
895 let outline = square(0.0, 0.0, 1000.0, 1000.0);
897 let small = glyph_path_from_outline(&outline, 1000, 7.8, Hinting::GridFit)
898 .expect("path")
899 .bbox()
900 .expect("bbox");
901 assert!(close(small.width(), 8.0), "{small:?}");
902 }
903
904 #[test]
905 fn rasterized_square_is_exact_and_placed() {
906 let outline = square(0.0, 0.0, 1000.0, 1000.0);
908 let bmp = rasterize_outline(&outline, 1000, 20.0, Hinting::None).expect("raster");
909 assert_eq!(bmp.width(), 20);
910 assert_eq!(bmp.height(), 20);
911 assert_eq!(bmp.left(), 0);
912 assert_eq!(bmp.top(), 20, "20 rows above the baseline");
913 assert!((bmp.ink() - 400.0).abs() < 1e-6, "ink {}", bmp.ink());
914 assert_eq!(bmp.coverage_at(0, 19), 255);
916 assert_eq!(bmp.coverage_at(19, 0), 255);
917 assert!(!bmp.is_empty());
918 }
919
920 #[test]
921 fn bitmap_placement_follows_the_glyph_origin() {
922 let outline = square(100.0, 0.0, 300.0, 1000.0);
925 let bmp = rasterize_outline(&outline, 1000, 10.0, Hinting::None).expect("raster");
926 assert_eq!(bmp.left(), 1);
927 assert_eq!(bmp.width(), 2);
928 assert_eq!(bmp.top(), 10);
929 let outline = square(-250.0, 0.0, 250.0, 1000.0);
931 let bmp = rasterize_outline(&outline, 1000, 10.0, Hinting::None).expect("raster");
932 assert_eq!(bmp.left(), -3);
935 assert_eq!(bmp.width(), 6);
936 assert_eq!(bmp.coverage_at(0, 0), 128, "half-covered left edge");
937 assert_eq!(bmp.coverage_at(5, 0), 128, "half-covered right edge");
938 assert!((bmp.ink() - 50.0).abs() < 0.05, "ink {}", bmp.ink());
939 }
940
941 #[test]
942 fn below_baseline_ink_extends_the_bitmap_downward() {
943 let outline = square(0.0, -300.0, 1000.0, 100.0);
947 let bmp = rasterize_outline(&outline, 1000, 10.0, Hinting::None).expect("raster");
948 assert_eq!(bmp.top(), 1);
949 assert_eq!(bmp.height(), 4);
950 assert_eq!(bmp.coverage_at(0, 0), 255, "above the baseline");
951 assert_eq!(bmp.coverage_at(0, 3), 255, "below the baseline");
952 assert!((bmp.ink() - 40.0).abs() < 0.05, "ink {}", bmp.ink());
953 }
954
955 #[test]
956 fn empty_outline_is_an_empty_bitmap_not_an_error() {
957 let bmp = rasterize_outline(&Outline::new(), 1000, 12.0, Hinting::None).expect("raster");
958 assert!(bmp.is_empty());
959 assert_eq!(bmp.width(), 0);
960 assert_eq!(bmp.ink(), 0.0);
961 let mut outline = Outline::new();
965 let mut p = Path::starting_at(100.0, 100.0);
966 p.close();
967 outline.push_contour(p);
968 let bmp = rasterize_outline(&outline, 1000, 12.0, Hinting::None).expect("raster");
969 assert!(bmp.ink() == 0.0, "a lone point has no ink");
970 assert!(bmp.ink_bounds().is_none(), "and no ink bounds");
971 }
972
973 #[test]
974 fn raster_size_errors_are_typed() {
975 let outline = square(0.0, 0.0, 1000.0, 1000.0);
976 assert!(matches!(
977 rasterize_outline(&outline, 1000, 0.0, Hinting::None),
978 Err(ShapeError::InvalidScale { .. })
979 ));
980 assert!(matches!(
981 rasterize_outline(&outline, 0, 12.0, Hinting::None),
982 Err(ShapeError::DegenerateUnitsPerEm)
983 ));
984 assert!(matches!(
986 rasterize_outline(&outline, 1000, 100_000.0, Hinting::None),
987 Err(ShapeError::RasterTooLarge { .. })
988 ));
989 }
990
991 #[test]
992 fn glyph_ink_tracks_the_outline_area() {
993 let outline = square(0.0, 0.0, 500.0, 400.0);
996 let bmp = rasterize_outline(&outline, 1000, 20.0, Hinting::None).expect("raster");
997 assert_eq!(bmp.width(), 10);
998 assert_eq!(bmp.height(), 8);
999 assert!((bmp.ink() - 80.0).abs() < 1e-6, "ink {}", bmp.ink());
1000 let big = rasterize_outline(&outline, 1000, 60.0, Hinting::None).expect("raster");
1002 assert!((big.ink() - 80.0 * 9.0).abs() < 1e-6, "ink {}", big.ink());
1003 }
1004
1005 #[test]
1006 fn rasterize_glyph_goes_through_the_font() {
1007 let mut outline = square(0.0, 0.0, 1000.0, 1000.0);
1008 let font = Font::builder()
1009 .units_per_em(1000)
1010 .glyph(Glyph::empty(GlyphId::NOTDEF, 500))
1011 .glyph(Glyph::new(GlyphId::new(1), 1000, 0, outline.clone()))
1012 .build()
1013 .expect("font");
1014 let bmp = rasterize_glyph(&font, GlyphId::new(1), 10.0, Hinting::None).expect("raster");
1015 assert_eq!(bmp.width(), 10);
1016 assert!((bmp.ink() - 100.0).abs() < 1e-6, "ink {}", bmp.ink());
1017 outline.contours_mut().clear();
1018 assert_eq!(outline.contours().len(), 0);
1019 match rasterize_glyph(&font, GlyphId::new(9), 10.0, Hinting::None).unwrap_err() {
1021 ShapeError::UnknownGlyph { glyph, glyph_count } => {
1022 assert_eq!(glyph, 9);
1023 assert_eq!(glyph_count, 2);
1024 }
1025 other => panic!("expected UnknownGlyph, got {other:?}"),
1026 }
1027 assert_eq!(
1028 ShapeError::UnknownGlyph {
1029 glyph: 9,
1030 glyph_count: 2
1031 }
1032 .to_string(),
1033 "glyph 9 requested but the font holds only 2"
1034 );
1035 }
1036
1037 #[test]
1038 fn glyph_path_from_a_font() {
1039 let font = Font::builder()
1040 .units_per_em(1000)
1041 .glyph(Glyph::empty(GlyphId::NOTDEF, 500))
1042 .glyph(Glyph::new(
1043 GlyphId::new(1),
1044 1000,
1045 0,
1046 square(0.0, 0.0, 500.0, 500.0),
1047 ))
1048 .build()
1049 .expect("font");
1050 let path = glyph_path(&font, GlyphId::new(1), 100.0, Hinting::None).expect("path");
1051 let b = path.bbox().expect("bbox");
1052 assert_eq!(b.width(), 50.0);
1053 assert_eq!(b.height(), 50.0);
1054 assert_eq!(b.min_y, -50.0, "the ink sits above the baseline");
1055 let blank = glyph_path(&font, GlyphId::NOTDEF, 12.0, Hinting::None).expect("path");
1057 assert!(blank.bbox().is_none() || blank.bbox().is_some_and(|r| r.is_empty()));
1058 assert!(glyph_path(&font, GlyphId::new(7), 12.0, Hinting::None).is_err());
1060 }
1061
1062 #[test]
1063 fn bitmap_accessors_are_bounds_checked() {
1064 let bmp = GlyphBitmap::new(
1065 4,
1066 3,
1067 1,
1068 2,
1069 vec![
1070 0, 0, 0, 0, 0, 255, 255, 0, 0, 255, 255, 0, ],
1074 );
1075 assert_eq!(bmp.coverage().len(), 12);
1076 assert_eq!(bmp.row(0).len(), 4);
1077 assert_eq!(bmp.row(1)[1], 255);
1078 assert!(bmp.row(3).is_empty());
1079 assert_eq!(bmp.coverage_at(3, 2), 0);
1080 assert_eq!(bmp.ink_bounds(), Some((1, 1, 2, 2)));
1081 assert!((bmp.ink() - 4.0).abs() < 1e-9);
1082 let moved = bmp.clone().translated(5, -5);
1083 assert_eq!(moved.left(), 6);
1084 assert_eq!(moved.top(), -3);
1085 assert_eq!(
1086 moved.coverage(),
1087 bmp.coverage(),
1088 "translation moves nothing else"
1089 );
1090 assert_eq!(moved.into_coverage().len(), 12);
1091 assert_eq!(GlyphBitmap::default(), GlyphBitmap::empty());
1092 let short = GlyphBitmap::new(100, 100, 0, 0, Vec::new());
1094 assert_eq!(short.coverage_at(50, 50), 0);
1095 assert!(short.row(50).is_empty());
1096 assert_eq!(short.ink_bounds(), None);
1097 assert!(short.ink() == 0.0);
1098 }
1099
1100 #[test]
1101 fn ink_bounds_is_none_for_a_blank_glyph() {
1102 let blank = GlyphBitmap::new(4, 4, 0, 0, vec![0u8; 16]);
1103 assert_eq!(blank.ink_bounds(), None);
1104 assert!(!blank.is_empty(), "it has pixels, just no ink");
1105 let dot = GlyphBitmap::new(2, 2, 0, 0, vec![0, 0, 0, 255]);
1107 assert_eq!(dot.ink_bounds(), Some((1, 1, 1, 1)));
1108 }
1109
1110 #[test]
1111 fn hinting_modes_toggle_and_report() {
1112 assert_eq!(Hinting::default(), Hinting::None);
1113 assert!(!Hinting::None.is_grid_fit());
1114 assert!(Hinting::GridFit.is_grid_fit());
1115 assert_eq!(Hinting::None.toggled(), Hinting::GridFit);
1116 assert_eq!(Hinting::GridFit.toggled(), Hinting::None);
1117 }
1118
1119 #[test]
1120 fn scaled_metrics_are_in_pixels() {
1121 let m = font_model::FontMetrics {
1122 ascender: 800,
1123 descender: -200,
1124 line_gap: 100,
1125 ..font_model::FontMetrics::default()
1126 };
1127 let d = DeviceMetrics::from_font(&m, 0.02);
1128 assert!(close(d.ascent, 16.0));
1129 assert!(close(d.descent, 4.0));
1130 assert!(close(d.line_gap, 2.0));
1131 assert!(close(d.line_height, 22.0));
1132 let font = font_model::build_stub_font(&[b'A' as u32]).expect("font");
1134 let d = scaled_metrics(&font, 1000.0).expect("metrics");
1135 assert!(close(d.ascent, f32::from(font.metrics().ascender)));
1136 assert!(matches!(
1137 scaled_metrics(&font, 0.0),
1138 Err(ShapeError::InvalidScale { .. })
1139 ));
1140 assert!(matches!(
1141 scaled_metrics(&font, f32::NAN),
1142 Err(ShapeError::InvalidScale { .. })
1143 ));
1144 }
1145
1146 #[test]
1147 fn em_size_is_the_size_itself_when_sane() {
1148 assert_eq!(em_size_px(12.0), 12.0);
1149 assert_eq!(em_size_px(0.0), 0.0);
1150 assert_eq!(em_size_px(-1.0), 0.0);
1151 assert_eq!(em_size_px(f32::NAN), 0.0);
1152 assert_eq!(em_size_px(f32::INFINITY), 0.0);
1153 }
1154
1155 #[test]
1156 fn non_finite_outline_coordinates_do_not_panic() {
1157 let mut outline = Outline::new();
1160 let mut p = Path::starting_at(0.0, 0.0);
1161 p.line_to(f32::NAN, 100.0);
1162 p.line_to(500.0, 500.0);
1163 p.close();
1164 outline.push_contour(p);
1165 let bmp = rasterize_outline(&outline, 1000, 10.0, Hinting::None).expect("raster");
1166 assert!(bmp.ink() > 0.0, "the good part still draws");
1167
1168 let mut wide = Outline::new();
1173 let mut q = Path::starting_at(0.0, 0.0);
1174 q.line_to(f32::INFINITY, 100.0);
1175 q.close();
1176 wide.push_contour(q);
1177 match rasterize_outline(&wide, 1000, 10.0, Hinting::None) {
1178 Ok(bmp) => assert!(bmp.is_empty() || bmp.ink() >= 0.0),
1179 Err(e) => assert!(
1180 matches!(e, ShapeError::RasterTooLarge { .. }),
1181 "unexpected error: {e:?}"
1182 ),
1183 }
1184 }
1185
1186 #[test]
1187 fn contours_without_a_move_to_are_skipped() {
1188 let mut outline = Outline::new();
1191 let mut p = Path::new();
1192 p.push(Command::LineTo(100.0, 100.0));
1193 p.push(Command::Close);
1194 outline.push_contour(p);
1195 let bmp = rasterize_outline(&outline, 1000, 10.0, Hinting::None).expect("raster");
1196 assert!(bmp.ink() == 0.0, "ink {}", bmp.ink());
1197 }
1198
1199 #[test]
1200 fn a_glyph_scales_linearly_with_size() {
1201 let outline = square(0.0, 0.0, 1000.0, 1000.0);
1202 let mut prev: Option<f64> = None;
1203 for size in [1.0f32, 2.0, 4.0, 8.0, 16.0, 32.0] {
1204 let bmp = rasterize_outline(&outline, 1000, size, Hinting::None).expect("raster");
1205 assert_eq!(bmp.width() as f32, size, "width at {size}");
1206 assert_eq!(bmp.height() as f32, size, "height at {size}");
1207 assert!(close(bmp.top() as f32, size), "top {}", bmp.top());
1208 if let Some(p) = prev {
1209 assert!((bmp.ink() / p - 4.0).abs() < 1e-9, "doubling the size");
1210 }
1211 prev = Some(bmp.ink());
1212 }
1213 }
1214}