/src/fontations/skrifa/src/metrics.rs
Line | Count | Source |
1 | | //! Global font and glyph specific metrics. |
2 | | //! |
3 | | //! Metrics are various measurements that define positioning and layout |
4 | | //! characteristics for a font. They come in two flavors: |
5 | | //! |
6 | | //! * Global metrics: these are applicable to all glyphs in a font and generally |
7 | | //! define values that are used for the layout of a collection of glyphs. For example, |
8 | | //! the ascent, descent and leading values determine the position of the baseline where |
9 | | //! a glyph should be rendered as well as the suggested spacing above and below it. |
10 | | //! |
11 | | //! * Glyph metrics: these apply to single glyphs. For example, the advance |
12 | | //! width value describes the distance between two consecutive glyphs on a line. |
13 | | //! |
14 | | //! ### Selecting an "instance" |
15 | | //! Both global and glyph specific metrics accept two additional pieces of information |
16 | | //! to select the desired instance of a font: |
17 | | //! * Size: represented by the [Size] type, this determines the scaling factor that is |
18 | | //! applied to all metrics. |
19 | | //! * Normalized variation coordinates: represented by the [LocationRef] type, |
20 | | //! these define the position in design space for a variable font. For a non-variable |
21 | | //! font, these coordinates are ignored and you can pass [LocationRef::default()] |
22 | | //! as an argument for this parameter. |
23 | | //! |
24 | | |
25 | | use read_fonts::{ |
26 | | tables::{ |
27 | | glyf::Glyf, gvar::Gvar, hmtx::LongMetric, hvar::Hvar, loca::Loca, os2::SelectionFlags, |
28 | | }, |
29 | | types::{BigEndian, Fixed, GlyphId}, |
30 | | FontRef, TableProvider, |
31 | | }; |
32 | | |
33 | | use crate::{ |
34 | | outline::{pen::ControlBoundsPen, DrawSettings}, |
35 | | MetadataProvider, |
36 | | }; |
37 | | |
38 | | use super::instance::{LocationRef, NormalizedCoord, Size}; |
39 | | |
40 | | /// Type for a bounding box with single precision floating point coordinates. |
41 | | pub type BoundingBox = read_fonts::types::BoundingBox<f32>; |
42 | | |
43 | | /// Metrics for a text decoration. |
44 | | /// |
45 | | /// This represents the suggested offset and thickness of an underline |
46 | | /// or strikeout text decoration. |
47 | | #[derive(Copy, Clone, PartialEq, Default, Debug)] |
48 | | pub struct Decoration { |
49 | | /// Offset to the top of the decoration from the baseline. |
50 | | pub offset: f32, |
51 | | /// Thickness of the decoration. |
52 | | pub thickness: f32, |
53 | | } |
54 | | |
55 | | /// Metrics that apply to all glyphs in a font. |
56 | | /// |
57 | | /// These are retrieved for a specific position in the design space. |
58 | | /// |
59 | | /// This metrics here are derived from the following tables: |
60 | | /// * [head](https://learn.microsoft.com/en-us/typography/opentype/spec/head): `units_per_em`, `bounds` |
61 | | /// * [maxp](https://learn.microsoft.com/en-us/typography/opentype/spec/maxp): `glyph_count` |
62 | | /// * [post](https://learn.microsoft.com/en-us/typography/opentype/spec/post): `is_monospace`, `italic_angle`, `underline` |
63 | | /// * [OS/2](https://learn.microsoft.com/en-us/typography/opentype/spec/os2): `average_width`, `cap_height`, |
64 | | /// `x_height`, `strikeout`, as well as the line metrics: `ascent`, `descent`, `leading` if the `USE_TYPOGRAPHIC_METRICS` |
65 | | /// flag is set or the `hhea` line metrics are zero (the Windows metrics are used as a last resort). |
66 | | /// * [hhea](https://learn.microsoft.com/en-us/typography/opentype/spec/hhea): `max_width`, as well as the line metrics: |
67 | | /// `ascent`, `descent`, `leading` if they are non-zero and the `USE_TYPOGRAPHIC_METRICS` flag is not set in the OS/2 table |
68 | | /// |
69 | | /// For variable fonts, deltas are computed using the [MVAR](https://learn.microsoft.com/en-us/typography/opentype/spec/MVAR) |
70 | | /// table. |
71 | | #[derive(Copy, Clone, PartialEq, Default, Debug)] |
72 | | pub struct Metrics { |
73 | | /// Number of font design units per em unit. |
74 | | pub units_per_em: u16, |
75 | | /// Number of glyphs in the font. |
76 | | pub glyph_count: u16, |
77 | | /// True if the font is not proportionally spaced. |
78 | | pub is_monospace: bool, |
79 | | /// Italic angle in counter-clockwise degrees from the vertical. Zero for upright text, |
80 | | /// negative for text that leans to the right. |
81 | | pub italic_angle: f32, |
82 | | /// Distance from the baseline to the top of the alignment box. |
83 | | pub ascent: f32, |
84 | | /// Distance from the baseline to the bottom of the alignment box. |
85 | | pub descent: f32, |
86 | | /// Recommended additional spacing between lines. |
87 | | pub leading: f32, |
88 | | /// Distance from the baseline to the top of a typical English capital. |
89 | | pub cap_height: Option<f32>, |
90 | | /// Distance from the baseline to the top of the lowercase "x" or |
91 | | /// similar character. |
92 | | pub x_height: Option<f32>, |
93 | | /// Average width of all non-zero width characters in the font. |
94 | | pub average_width: Option<f32>, |
95 | | /// Maximum advance width of all characters in the font. |
96 | | pub max_width: Option<f32>, |
97 | | /// Metrics for an underline decoration. |
98 | | pub underline: Option<Decoration>, |
99 | | /// Metrics for a strikeout decoration. |
100 | | pub strikeout: Option<Decoration>, |
101 | | /// Union of minimum and maximum extents for all glyphs in the font. |
102 | | pub bounds: Option<BoundingBox>, |
103 | | } |
104 | | |
105 | | impl Metrics { |
106 | | /// Creates new metrics for the given font, size, and location in |
107 | | /// normalized variation space. |
108 | 0 | pub fn new<'a>(font: &FontRef<'a>, size: Size, location: impl Into<LocationRef<'a>>) -> Self { |
109 | 0 | let head = font.head(); |
110 | 0 | let mut metrics = Metrics { |
111 | 0 | units_per_em: head.map(|head| head.units_per_em()).unwrap_or_default(), |
112 | 0 | ..Default::default() |
113 | | }; |
114 | 0 | let coords = location.into().effective_coords(); |
115 | 0 | let scale = size.linear_scale(metrics.units_per_em); |
116 | 0 | if let Ok(head) = font.head() { |
117 | 0 | metrics.bounds = Some(BoundingBox { |
118 | 0 | x_min: head.x_min() as f32 * scale, |
119 | 0 | y_min: head.y_min() as f32 * scale, |
120 | 0 | x_max: head.x_max() as f32 * scale, |
121 | 0 | y_max: head.y_max() as f32 * scale, |
122 | 0 | }); |
123 | 0 | } |
124 | 0 | if let Ok(maxp) = font.maxp() { |
125 | 0 | metrics.glyph_count = maxp.num_glyphs(); |
126 | 0 | } |
127 | 0 | if let Ok(post) = font.post() { |
128 | 0 | metrics.is_monospace = post.is_fixed_pitch() != 0; |
129 | 0 | metrics.italic_angle = post.italic_angle().to_f64() as f32; |
130 | 0 | metrics.underline = Some(Decoration { |
131 | 0 | offset: post.underline_position().to_i16() as f32 * scale, |
132 | 0 | thickness: post.underline_thickness().to_i16() as f32 * scale, |
133 | 0 | }); |
134 | 0 | } |
135 | 0 | let hhea = font.hhea(); |
136 | 0 | if let Ok(hhea) = &hhea { |
137 | 0 | metrics.max_width = Some(hhea.advance_width_max().to_u16() as f32 * scale); |
138 | 0 | } |
139 | | // Choosing proper line metrics is a challenge due to the changing |
140 | | // spec, backward compatibility and broken fonts. |
141 | | // |
142 | | // We use the same strategy as FreeType: |
143 | | // 1. Use the OS/2 metrics if the table exists and the USE_TYPO_METRICS |
144 | | // flag is set. |
145 | | // 2. Otherwise, use the hhea metrics. |
146 | | // 3. If hhea metrics are zero and the OS/2 table exists: |
147 | | // 3a. Use the typo metrics if they are non-zero |
148 | | // 3b. Otherwise, use the win metrics |
149 | | // |
150 | | // See: https://github.com/freetype/freetype/blob/5c37b6406258ec0d7ab64b8619c5ea2c19e3c69a/src/sfnt/sfobjs.c#L1311 |
151 | 0 | let os2 = font.os2().ok(); |
152 | 0 | let mut used_typo_metrics = false; |
153 | 0 | if let Some(os2) = &os2 { |
154 | 0 | if os2 |
155 | 0 | .fs_selection() |
156 | 0 | .contains(SelectionFlags::USE_TYPO_METRICS) |
157 | 0 | { |
158 | 0 | metrics.ascent = os2.s_typo_ascender() as f32 * scale; |
159 | 0 | metrics.descent = os2.s_typo_descender() as f32 * scale; |
160 | 0 | metrics.leading = os2.s_typo_line_gap() as f32 * scale; |
161 | 0 | used_typo_metrics = true; |
162 | 0 | } |
163 | 0 | metrics.average_width = Some(os2.x_avg_char_width() as f32 * scale); |
164 | 0 | metrics.cap_height = os2.s_cap_height().map(|v| v as f32 * scale); |
165 | 0 | metrics.x_height = os2.sx_height().map(|v| v as f32 * scale); |
166 | 0 | metrics.strikeout = Some(Decoration { |
167 | 0 | offset: os2.y_strikeout_position() as f32 * scale, |
168 | 0 | thickness: os2.y_strikeout_size() as f32 * scale, |
169 | 0 | }); |
170 | 0 | } |
171 | 0 | if !used_typo_metrics { |
172 | 0 | if let Ok(hhea) = font.hhea() { |
173 | 0 | metrics.ascent = hhea.ascender().to_i16() as f32 * scale; |
174 | 0 | metrics.descent = hhea.descender().to_i16() as f32 * scale; |
175 | 0 | metrics.leading = hhea.line_gap().to_i16() as f32 * scale; |
176 | 0 | } |
177 | 0 | if metrics.ascent == 0.0 && metrics.descent == 0.0 { |
178 | 0 | if let Some(os2) = &os2 { |
179 | 0 | if os2.s_typo_ascender() != 0 || os2.s_typo_descender() != 0 { |
180 | 0 | metrics.ascent = os2.s_typo_ascender() as f32 * scale; |
181 | 0 | metrics.descent = os2.s_typo_descender() as f32 * scale; |
182 | 0 | metrics.leading = os2.s_typo_line_gap() as f32 * scale; |
183 | 0 | } else { |
184 | 0 | metrics.ascent = os2.us_win_ascent() as f32 * scale; |
185 | 0 | // Win descent is always positive while other descent values are negative. Negate it |
186 | 0 | // to ensure we return consistent metrics. |
187 | 0 | metrics.descent = -(os2.us_win_descent() as f32 * scale); |
188 | 0 | } |
189 | 0 | } |
190 | 0 | } |
191 | 0 | } |
192 | 0 | if let (Ok(mvar), true) = (font.mvar(), !coords.is_empty()) { |
193 | | use read_fonts::tables::mvar::tags::*; |
194 | 0 | let metric_delta = |
195 | 0 | |tag| mvar.metric_delta(tag, coords).unwrap_or_default().to_f64() as f32 * scale; |
196 | 0 | metrics.ascent += metric_delta(HASC); |
197 | 0 | metrics.descent += metric_delta(HDSC); |
198 | 0 | metrics.leading += metric_delta(HLGP); |
199 | 0 | if let Some(cap_height) = &mut metrics.cap_height { |
200 | 0 | *cap_height += metric_delta(CPHT); |
201 | 0 | } |
202 | 0 | if let Some(x_height) = &mut metrics.x_height { |
203 | 0 | *x_height += metric_delta(XHGT); |
204 | 0 | } |
205 | 0 | if let Some(underline) = &mut metrics.underline { |
206 | 0 | underline.offset += metric_delta(UNDO); |
207 | 0 | underline.thickness += metric_delta(UNDS); |
208 | 0 | } |
209 | 0 | if let Some(strikeout) = &mut metrics.strikeout { |
210 | 0 | strikeout.offset += metric_delta(STRO); |
211 | 0 | strikeout.thickness += metric_delta(STRS); |
212 | 0 | } |
213 | 0 | } |
214 | 0 | metrics |
215 | 0 | } |
216 | | } |
217 | | |
218 | | /// Glyph specific metrics. |
219 | | #[derive(Clone)] |
220 | | pub struct GlyphMetrics<'a> { |
221 | | font: FontRef<'a>, |
222 | | size: Size, |
223 | | glyph_count: u32, |
224 | | fixed_scale: FixedScaleFactor, |
225 | | h_metrics: &'a [LongMetric], |
226 | | default_advance_width: u16, |
227 | | lsbs: &'a [BigEndian<i16>], |
228 | | hvar: Option<Hvar<'a>>, |
229 | | gvar: Option<Gvar<'a>>, |
230 | | loca_glyf: Option<(Loca<'a>, Glyf<'a>)>, |
231 | | coords: &'a [NormalizedCoord], |
232 | | } |
233 | | |
234 | | impl<'a> GlyphMetrics<'a> { |
235 | | /// Creates new glyph metrics from the given font, size, and location in |
236 | | /// normalized variation space. |
237 | 0 | pub fn new(font: &FontRef<'a>, size: Size, location: impl Into<LocationRef<'a>>) -> Self { |
238 | 0 | let glyph_count = font |
239 | 0 | .maxp() |
240 | 0 | .map(|maxp| maxp.num_glyphs() as u32) Unexecuted instantiation: <skrifa::metrics::GlyphMetrics>::new::<skrifa::instance::LocationRef>::{closure#0}Unexecuted instantiation: <skrifa::metrics::GlyphMetrics>::new::<&[font_types::fixed::F2Dot14]>::{closure#0} |
241 | 0 | .unwrap_or_default(); |
242 | 0 | let upem = font |
243 | 0 | .head() |
244 | 0 | .map(|head| head.units_per_em()) Unexecuted instantiation: <skrifa::metrics::GlyphMetrics>::new::<skrifa::instance::LocationRef>::{closure#1}Unexecuted instantiation: <skrifa::metrics::GlyphMetrics>::new::<&[font_types::fixed::F2Dot14]>::{closure#1} |
245 | 0 | .unwrap_or_default(); |
246 | 0 | let fixed_scale = FixedScaleFactor(size.fixed_linear_scale(upem)); |
247 | 0 | let coords = location.into().effective_coords(); |
248 | 0 | let (h_metrics, default_advance_width, lsbs) = font |
249 | 0 | .hmtx() |
250 | 0 | .map(|hmtx| { |
251 | 0 | let h_metrics = hmtx.h_metrics(); |
252 | 0 | let default_advance_width = h_metrics.last().map(|m| m.advance.get()).unwrap_or(0); Unexecuted instantiation: <skrifa::metrics::GlyphMetrics>::new::<skrifa::instance::LocationRef>::{closure#2}::{closure#0}Unexecuted instantiation: <skrifa::metrics::GlyphMetrics>::new::<&[font_types::fixed::F2Dot14]>::{closure#2}::{closure#0} |
253 | 0 | let lsbs = hmtx.left_side_bearings(); |
254 | 0 | (h_metrics, default_advance_width, lsbs) |
255 | 0 | }) Unexecuted instantiation: <skrifa::metrics::GlyphMetrics>::new::<skrifa::instance::LocationRef>::{closure#2}Unexecuted instantiation: <skrifa::metrics::GlyphMetrics>::new::<&[font_types::fixed::F2Dot14]>::{closure#2} |
256 | 0 | .unwrap_or_default(); |
257 | 0 | let hvar = font.hvar().ok(); |
258 | 0 | let gvar = font.gvar().ok(); |
259 | 0 | let loca_glyf = if let (Ok(loca), Ok(glyf)) = (font.loca(None), font.glyf()) { |
260 | 0 | Some((loca, glyf)) |
261 | | } else { |
262 | 0 | None |
263 | | }; |
264 | 0 | Self { |
265 | 0 | font: font.clone(), |
266 | 0 | size, |
267 | 0 | glyph_count, |
268 | 0 | fixed_scale, |
269 | 0 | h_metrics, |
270 | 0 | default_advance_width, |
271 | 0 | lsbs, |
272 | 0 | hvar, |
273 | 0 | gvar, |
274 | 0 | loca_glyf, |
275 | 0 | coords, |
276 | 0 | } |
277 | 0 | } Unexecuted instantiation: <skrifa::metrics::GlyphMetrics>::new::<skrifa::instance::LocationRef> Unexecuted instantiation: <skrifa::metrics::GlyphMetrics>::new::<&[font_types::fixed::F2Dot14]> |
278 | | |
279 | | /// Returns the number of available glyphs in the font. |
280 | 0 | pub fn glyph_count(&self) -> u32 { |
281 | 0 | self.glyph_count |
282 | 0 | } |
283 | | |
284 | | /// Returns the advance width for the specified glyph. |
285 | | /// |
286 | | /// If normalized coordinates were provided when constructing glyph metrics and |
287 | | /// an `HVAR` table is present, applies the appropriate delta. |
288 | | /// |
289 | | /// Returns `None` if `glyph_id >= self.glyph_count()` or the underlying font |
290 | | /// data is invalid. |
291 | 0 | pub fn advance_width(&self, glyph_id: GlyphId) -> Option<f32> { |
292 | 0 | if glyph_id.to_u32() >= self.glyph_count { |
293 | 0 | return None; |
294 | 0 | } |
295 | 0 | let mut advance = self |
296 | 0 | .h_metrics |
297 | 0 | .get(glyph_id.to_u32() as usize) |
298 | 0 | .map(|metric| metric.advance()) |
299 | 0 | .unwrap_or(self.default_advance_width) as i32; |
300 | 0 | if let Some(hvar) = &self.hvar { |
301 | 0 | advance += hvar |
302 | 0 | .advance_delta(glyph_id, self.coords) |
303 | | // The delta is exact, and this rounds it to a whole design |
304 | | // unit before it is added. |
305 | | // https://github.com/freetype/freetype/blob/7838c78f53f206ac5b8e9cefde548aa81cb00cf4/src/truetype/ttgxvar.c#L1027 |
306 | 0 | .map(|delta| delta.to_i32()) |
307 | 0 | .unwrap_or(0); |
308 | 0 | } else if self.gvar.is_some() { |
309 | 0 | advance += self.metric_deltas_from_gvar(glyph_id).unwrap_or_default()[1]; |
310 | 0 | } |
311 | 0 | Some(self.fixed_scale.apply(advance)) |
312 | 0 | } |
313 | | |
314 | | /// Returns the left side bearing for the specified glyph. |
315 | | /// |
316 | | /// If normalized coordinates were provided when constructing glyph metrics and |
317 | | /// an `HVAR` table is present, applies the appropriate delta. |
318 | | /// |
319 | | /// Returns `None` if `glyph_id >= self.glyph_count()` or the underlying font |
320 | | /// data is invalid. |
321 | 0 | pub fn left_side_bearing(&self, glyph_id: GlyphId) -> Option<f32> { |
322 | 0 | if glyph_id.to_u32() >= self.glyph_count { |
323 | 0 | return None; |
324 | 0 | } |
325 | 0 | let gid_index = glyph_id.to_u32() as usize; |
326 | 0 | let mut lsb = self |
327 | 0 | .h_metrics |
328 | 0 | .get(gid_index) |
329 | 0 | .map(|metric| metric.side_bearing()) |
330 | 0 | .unwrap_or_else(|| { |
331 | 0 | self.lsbs |
332 | 0 | .get(gid_index.saturating_sub(self.h_metrics.len())) |
333 | 0 | .map(|lsb| lsb.get()) |
334 | 0 | .unwrap_or_default() |
335 | 0 | }) as i32; |
336 | 0 | if let Some(hvar) = &self.hvar { |
337 | 0 | lsb += hvar |
338 | 0 | .lsb_delta(glyph_id, self.coords) |
339 | | // The delta is exact, and this rounds it to a whole design |
340 | | // unit before it is added. |
341 | | // https://github.com/freetype/freetype/blob/7838c78f53f206ac5b8e9cefde548aa81cb00cf4/src/truetype/ttgxvar.c#L1027 |
342 | 0 | .map(|delta| delta.to_i32()) |
343 | 0 | .unwrap_or(0); |
344 | 0 | } else if self.gvar.is_some() { |
345 | 0 | lsb += self.metric_deltas_from_gvar(glyph_id).unwrap_or_default()[0]; |
346 | 0 | } |
347 | 0 | Some(self.fixed_scale.apply(lsb)) |
348 | 0 | } |
349 | | |
350 | | /// Returns the bounding box for the specified glyph. |
351 | | /// |
352 | | /// Returns `None` if `glyph_id >= self.glyph_count()`, the underlying font |
353 | | /// data is invalid. |
354 | 0 | pub fn bounds(&self, glyph_id: GlyphId) -> Option<BoundingBox> { |
355 | 0 | if self.gvar.is_some() || self.font.cff().ok().is_some() || self.font.cff2().ok().is_some() |
356 | | { |
357 | 0 | return self.bounds_from_outline(glyph_id); |
358 | 0 | } |
359 | 0 | let (loca, glyf) = self.loca_glyf.as_ref()?; |
360 | 0 | Some(match loca.get(glyph_id, glyf)?.glyph() { |
361 | 0 | Some(glyph) => BoundingBox { |
362 | 0 | x_min: self.fixed_scale.apply(glyph.x_min() as i32), |
363 | 0 | y_min: self.fixed_scale.apply(glyph.y_min() as i32), |
364 | 0 | x_max: self.fixed_scale.apply(glyph.x_max() as i32), |
365 | 0 | y_max: self.fixed_scale.apply(glyph.y_max() as i32), |
366 | 0 | }, |
367 | | // Empty glyphs have an empty bounding box |
368 | 0 | None => BoundingBox::default(), |
369 | | }) |
370 | 0 | } |
371 | | } |
372 | | |
373 | | impl GlyphMetrics<'_> { |
374 | 0 | fn metric_deltas_from_gvar(&self, glyph_id: GlyphId) -> Option<[i32; 2]> { |
375 | 0 | let (loca, glyf) = self.loca_glyf.as_ref()?; |
376 | 0 | let mut deltas = self |
377 | 0 | .gvar |
378 | 0 | .as_ref()? |
379 | 0 | .phantom_point_deltas(glyf, loca, self.coords, glyph_id) |
380 | 0 | .ok() |
381 | 0 | .flatten()?; |
382 | 0 | deltas[1] -= deltas[0]; |
383 | 0 | Some([deltas[0], deltas[1]].map(|delta| delta.x.to_i32())) |
384 | 0 | } |
385 | | |
386 | 0 | fn bounds_from_outline(&self, glyph_id: GlyphId) -> Option<BoundingBox> { |
387 | 0 | if let Some(outline) = self.font.outline_glyphs().get(glyph_id) { |
388 | 0 | let settings = DrawSettings::unhinted(self.size, self.coords); |
389 | 0 | let mut pen = ControlBoundsPen::default(); |
390 | 0 | outline.draw(settings, &mut pen).ok()?; |
391 | 0 | pen.bounding_box() |
392 | | } else { |
393 | 0 | None |
394 | | } |
395 | 0 | } |
396 | | } |
397 | | |
398 | | #[derive(Copy, Clone)] |
399 | | struct FixedScaleFactor(Fixed); |
400 | | |
401 | | impl FixedScaleFactor { |
402 | | #[inline(always)] |
403 | 0 | fn apply(self, value: i32) -> f32 { |
404 | | // Match FreeType metric scaling |
405 | | // <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/base/ftadvanc.c#L50> |
406 | 0 | self.0 |
407 | 0 | .mul_div(Fixed::from_bits(value), Fixed::from_bits(64)) |
408 | 0 | .to_f32() |
409 | 0 | } |
410 | | } |
411 | | |
412 | | #[cfg(test)] |
413 | | mod tests { |
414 | | use super::*; |
415 | | use font_test_data::{NOTO_SANS_JP_CFF, SIMPLE_GLYF, VAZIRMATN_VAR}; |
416 | | use read_fonts::FontRef; |
417 | | |
418 | | #[test] |
419 | | fn metrics() { |
420 | | let font = FontRef::new(SIMPLE_GLYF).unwrap(); |
421 | | let metrics = font.metrics(Size::unscaled(), LocationRef::default()); |
422 | | let expected = Metrics { |
423 | | units_per_em: 1024, |
424 | | glyph_count: 3, |
425 | | bounds: Some(BoundingBox { |
426 | | x_min: 51.0, |
427 | | y_min: -250.0, |
428 | | x_max: 998.0, |
429 | | y_max: 950.0, |
430 | | }), |
431 | | average_width: Some(1275.0), |
432 | | max_width: None, |
433 | | x_height: Some(512.0), |
434 | | cap_height: Some(717.0), |
435 | | is_monospace: false, |
436 | | italic_angle: 0.0, |
437 | | ascent: 950.0, |
438 | | descent: -250.0, |
439 | | leading: 0.0, |
440 | | underline: None, |
441 | | strikeout: Some(Decoration { |
442 | | offset: 307.0, |
443 | | thickness: 51.0, |
444 | | }), |
445 | | }; |
446 | | assert_eq!(metrics, expected); |
447 | | } |
448 | | |
449 | | #[test] |
450 | | fn metrics_missing_os2() { |
451 | | let font = FontRef::new(VAZIRMATN_VAR).unwrap(); |
452 | | let metrics = font.metrics(Size::unscaled(), LocationRef::default()); |
453 | | let expected = Metrics { |
454 | | units_per_em: 2048, |
455 | | glyph_count: 4, |
456 | | bounds: Some(BoundingBox { |
457 | | x_min: 29.0, |
458 | | y_min: 0.0, |
459 | | x_max: 1310.0, |
460 | | y_max: 1847.0, |
461 | | }), |
462 | | average_width: None, |
463 | | max_width: Some(1336.0), |
464 | | x_height: None, |
465 | | cap_height: None, |
466 | | is_monospace: false, |
467 | | italic_angle: 0.0, |
468 | | ascent: 2100.0, |
469 | | descent: -1100.0, |
470 | | leading: 0.0, |
471 | | underline: None, |
472 | | strikeout: None, |
473 | | }; |
474 | | assert_eq!(metrics, expected); |
475 | | } |
476 | | |
477 | | #[test] |
478 | | fn glyph_metrics() { |
479 | | let font = FontRef::new(VAZIRMATN_VAR).unwrap(); |
480 | | let glyph_metrics = font.glyph_metrics(Size::unscaled(), LocationRef::default()); |
481 | | // (advance_width, lsb) in glyph order |
482 | | let expected = &[ |
483 | | (908.0, 100.0), |
484 | | (1336.0, 29.0), |
485 | | (1336.0, 29.0), |
486 | | (633.0, 57.0), |
487 | | ]; |
488 | | let result = (0..4) |
489 | | .map(|i| { |
490 | | let gid = GlyphId::new(i as u32); |
491 | | let advance_width = glyph_metrics.advance_width(gid).unwrap(); |
492 | | let lsb = glyph_metrics.left_side_bearing(gid).unwrap(); |
493 | | (advance_width, lsb) |
494 | | }) |
495 | | .collect::<Vec<_>>(); |
496 | | assert_eq!(expected, &result[..]); |
497 | | } |
498 | | |
499 | | /// Asserts that the results generated with Size::unscaled() and |
500 | | /// Size::new(upem) are equal. |
501 | | /// |
502 | | /// See <https://github.com/googlefonts/fontations/issues/590#issuecomment-1711595882> |
503 | | #[test] |
504 | | fn glyph_metrics_unscaled_matches_upem_scale() { |
505 | | let font = FontRef::new(VAZIRMATN_VAR).unwrap(); |
506 | | let upem = font.head().unwrap().units_per_em() as f32; |
507 | | let unscaled_metrics = font.glyph_metrics(Size::unscaled(), LocationRef::default()); |
508 | | let upem_metrics = font.glyph_metrics(Size::new(upem), LocationRef::default()); |
509 | | for i in 0..unscaled_metrics.glyph_count() { |
510 | | let gid = GlyphId::new(i); |
511 | | assert_eq!( |
512 | | unscaled_metrics.advance_width(gid), |
513 | | upem_metrics.advance_width(gid) |
514 | | ); |
515 | | assert_eq!( |
516 | | unscaled_metrics.left_side_bearing(gid), |
517 | | upem_metrics.left_side_bearing(gid) |
518 | | ); |
519 | | } |
520 | | } |
521 | | |
522 | | #[test] |
523 | | fn glyph_metrics_var() { |
524 | | let font = FontRef::new(VAZIRMATN_VAR).unwrap(); |
525 | | let coords = &[NormalizedCoord::from_f32(-0.8)]; |
526 | | let glyph_metrics = font.glyph_metrics(Size::unscaled(), LocationRef::new(coords)); |
527 | | // (advance_width, lsb) in glyph order |
528 | | let expected = &[ |
529 | | (908.0, 100.0), |
530 | | (1246.0, 29.0), |
531 | | (1246.0, 29.0), |
532 | | (556.0, 57.0), |
533 | | ]; |
534 | | let result = (0..4) |
535 | | .map(|i| { |
536 | | let gid = GlyphId::new(i as u32); |
537 | | let advance_width = glyph_metrics.advance_width(gid).unwrap(); |
538 | | let lsb = glyph_metrics.left_side_bearing(gid).unwrap(); |
539 | | (advance_width, lsb) |
540 | | }) |
541 | | .collect::<Vec<_>>(); |
542 | | assert_eq!(expected, &result[..]); |
543 | | |
544 | | // Check bounds |
545 | | let coords = &[NormalizedCoord::from_f32(-1.0)]; |
546 | | let glyph_metrics = font.glyph_metrics(Size::unscaled(), LocationRef::new(coords)); |
547 | | let bounds = glyph_metrics.bounds(GlyphId::new(1)).unwrap(); |
548 | | assert_eq!( |
549 | | bounds, |
550 | | BoundingBox { |
551 | | x_min: 33.0, |
552 | | y_min: 0.0, |
553 | | x_max: 1189.0, |
554 | | y_max: 1456.0 |
555 | | } |
556 | | ); |
557 | | } |
558 | | |
559 | | #[test] |
560 | | fn glyph_metrics_cff() { |
561 | | let font = FontRef::new(NOTO_SANS_JP_CFF).unwrap(); |
562 | | let glyph_metrics = font.glyph_metrics(Size::unscaled(), LocationRef::default()); |
563 | | let bounds = glyph_metrics.bounds(GlyphId::new(34)).unwrap(); |
564 | | assert_eq!( |
565 | | bounds, |
566 | | BoundingBox { |
567 | | x_min: 4.0, |
568 | | y_min: 0.0, |
569 | | x_max: 604.0, |
570 | | y_max: 733.0 |
571 | | } |
572 | | ); |
573 | | } |
574 | | |
575 | | #[test] |
576 | | fn glyph_metrics_missing_hvar() { |
577 | | let font = FontRef::new(VAZIRMATN_VAR).unwrap(); |
578 | | let glyph_count = font.maxp().unwrap().num_glyphs(); |
579 | | // Test a few different locations in variation space |
580 | | for coord in [-1.0, -0.8, 0.0, 0.75, 1.0] { |
581 | | let coords = &[NormalizedCoord::from_f32(coord)]; |
582 | | let location = LocationRef::new(coords); |
583 | | let glyph_metrics = font.glyph_metrics(Size::unscaled(), location); |
584 | | let mut glyph_metrics_no_hvar = glyph_metrics.clone(); |
585 | | // Setting hvar to None forces use of gvar for metric deltas |
586 | | glyph_metrics_no_hvar.hvar = None; |
587 | | for gid in 0..glyph_count { |
588 | | let gid = GlyphId::from(gid); |
589 | | assert_eq!( |
590 | | glyph_metrics.advance_width(gid), |
591 | | glyph_metrics_no_hvar.advance_width(gid) |
592 | | ); |
593 | | assert_eq!( |
594 | | glyph_metrics.left_side_bearing(gid), |
595 | | glyph_metrics_no_hvar.left_side_bearing(gid) |
596 | | ); |
597 | | } |
598 | | } |
599 | | } |
600 | | |
601 | | /// Ensure our fixed point scaling code matches FreeType for advances. |
602 | | /// |
603 | | /// <https://github.com/googlefonts/fontations/issues/590> |
604 | | #[test] |
605 | | fn match_freetype_glyph_metric_scaling() { |
606 | | // fontations: |
607 | | // gid: 36 advance: 15.33600044250488281250 gid: 68 advance: 13.46399974822998046875 gid: 47 advance: 12.57600021362304687500 gid: 79 advance: 6.19199991226196289062 |
608 | | // ft: |
609 | | // gid: 36 advance: 15.33595275878906250000 gid: 68 advance: 13.46395874023437500000 gid: 47 advance: 12.57595825195312500000 gid: 79 advance: 6.19198608398437500000 |
610 | | // with font.setSize(24); |
611 | | // |
612 | | // Raw advances for gids 36, 68, 47, and 79 in NotoSans-Regular |
613 | | let font_unit_advances = [639, 561, 524, 258]; |
614 | | #[allow(clippy::excessive_precision)] |
615 | | let scaled_advances = [ |
616 | | 15.33595275878906250000, |
617 | | 13.46395874023437500000, |
618 | | 12.57595825195312500000, |
619 | | 6.19198608398437500000, |
620 | | ]; |
621 | | let fixed_scale = FixedScaleFactor(Size::new(24.0).fixed_linear_scale(1000)); |
622 | | for (font_unit_advance, expected_scaled_advance) in |
623 | | font_unit_advances.iter().zip(scaled_advances) |
624 | | { |
625 | | let scaled_advance = fixed_scale.apply(*font_unit_advance); |
626 | | assert_eq!(scaled_advance, expected_scaled_advance); |
627 | | } |
628 | | } |
629 | | } |