1use std::fmt::{Debug, Error, Formatter};
6use std::ops::{Deref, RangeInclusive};
7use std::sync::Arc;
8
9use atomic_refcell::{AtomicRef, AtomicRefCell};
10use malloc_size_of_derive::MallocSizeOf;
11use serde::{Deserialize, Serialize};
12use servo_arc::Arc as ServoArc;
13use skrifa::Font as SkrifaFont;
14use skrifa::font::attribute::Style;
15use style::computed_values::font_style::T as FontStyle;
16use style::computed_values::font_width::T as FontWidth;
17use style::font_face::{ComputedFontStyleRange, ComputedFontWeightRange, ComputedFontWidthRange};
18use style::values::computed::font::FontWeight;
19
20use crate::tag::{WDTH, WGHT};
21use crate::{CSSFontFaceDescriptors, FontDescriptor, FontFaceRuleInfo, FontIdentifier};
22
23#[derive(Clone, Debug, MallocSizeOf)]
25pub struct FontTemplateRef(#[conditional_malloc_size_of] Arc<AtomicRefCell<FontTemplate>>);
26
27impl FontTemplateRef {
28 pub fn new(template: FontTemplate) -> Self {
29 Self(Arc::new(AtomicRefCell::new(template)))
30 }
31}
32
33impl Deref for FontTemplateRef {
34 type Target = Arc<AtomicRefCell<FontTemplate>>;
35 fn deref(&self) -> &Self::Target {
36 &self.0
37 }
38}
39
40#[derive(Clone, Debug, Deserialize, Hash, MallocSizeOf, PartialEq, Serialize)]
45pub struct FontTemplateDescriptor {
46 pub weight: ComputedFontWeightRange,
47 pub width: ComputedFontWidthRange,
48 pub style: ComputedFontStyleRange,
49 pub unicode_range: Option<Vec<RangeInclusive<u32>>>,
50}
51
52impl Default for FontTemplateDescriptor {
53 fn default() -> Self {
54 Self::new(FontWeight::normal(), FontWidth::NORMAL, FontStyle::NORMAL)
55 }
56}
57
58impl FontTemplateDescriptor {
59 pub fn from_skrifa_font(font: &SkrifaFont) -> FontTemplateDescriptor {
62 let attributes = font.default_attributes();
63
64 let mut descriptor = Self::new(
65 FontWeight::from_float(attributes.weight.value()),
66 FontWidth::from_percentage(attributes.width.ratio()),
67 match attributes.style {
68 Style::Normal => FontStyle::NORMAL,
69 Style::Oblique(Some(degrees)) => FontStyle::oblique(degrees),
70 Style::Oblique(None) => FontStyle::OBLIQUE,
71 Style::Italic => FontStyle::ITALIC,
72 },
73 );
74
75 for axis in font.axes().iter() {
76 match axis.tag() {
77 WDTH => {
78 descriptor.width = ComputedFontWidthRange(
79 FontWidth::from_percentage(axis.min_value() / 100.0),
80 FontWidth::from_percentage(axis.max_value() / 100.0),
81 )
82 },
83 WGHT => {
84 descriptor.weight = ComputedFontWeightRange(
85 FontWeight::from_float(axis.min_value()),
86 FontWeight::from_float(axis.max_value()),
87 )
88 },
89 _ => {},
90 }
91 }
92
93 descriptor
94 }
95
96 #[inline]
97 pub fn new(weight: FontWeight, width: FontWidth, style: FontStyle) -> Self {
98 Self {
99 weight: ComputedFontWeightRange(weight, weight),
100 width: ComputedFontWidthRange(width, width),
101 style: ComputedFontStyleRange(style, style),
102 unicode_range: None,
103 }
104 }
105
106 pub fn is_variation_font(&self) -> bool {
107 self.weight.0 != self.weight.1 ||
108 self.width.0 != self.width.1 ||
109 self.style.0 != self.style.1
110 }
111
112 #[inline]
119 fn distance_from(&self, target: &FontDescriptor) -> f32 {
120 let width_distance = target.width.match_distance(&self.width);
121 let style_distance = target.style.match_distance(&self.style);
122 let weight_distance = target.weight.match_distance(&self.weight);
123
124 assert!((0.0..=2000.0).contains(&width_distance));
127 assert!((0.0..=500.0).contains(&style_distance));
128 assert!((0.0..=1600.0).contains(&weight_distance));
129
130 const WIDTH_FACTOR: f32 = 1.0e8;
139 const STYLE_FACTOR: f32 = 1.0e4;
140 const WEIGHT_FACTOR: f32 = 1.0e0;
141
142 width_distance * WIDTH_FACTOR +
143 style_distance * STYLE_FACTOR +
144 weight_distance * WEIGHT_FACTOR
145 }
146
147 fn matches(&self, descriptor_to_match: &FontDescriptor) -> bool {
148 self.weight.0 <= descriptor_to_match.weight &&
149 self.weight.1 >= descriptor_to_match.weight &&
150 self.style.0 <= descriptor_to_match.style &&
151 self.style.1 >= descriptor_to_match.style &&
152 self.width.0 <= descriptor_to_match.width &&
153 self.width.1 >= descriptor_to_match.width
154 }
155
156 pub fn override_values_with_css_font_template_descriptors(
157 &mut self,
158 css_font_template_descriptors: &CSSFontFaceDescriptors,
159 ) {
160 if let Some(ref weight) = css_font_template_descriptors.weight {
161 self.weight = weight.clone();
162 }
163 if let Some(ref style) = css_font_template_descriptors.style {
164 self.style = style.clone();
165 }
166 if let Some(ref width) = css_font_template_descriptors.width {
167 self.width = width.clone();
168 }
169 if let Some(ref unicode_range) = css_font_template_descriptors.unicode_range {
170 self.unicode_range = Some(unicode_range.clone());
171 }
172 }
173}
174
175#[derive(Clone, Deserialize, MallocSizeOf, Serialize)]
179pub struct FontTemplate {
180 pub identifier: FontIdentifier,
181 pub descriptor: FontTemplateDescriptor,
182
183 #[serde(skip)]
186 #[conditional_malloc_size_of]
187 pub font_face_rule: Option<ServoArc<FontFaceRuleInfo>>,
188}
189
190impl Debug for FontTemplate {
191 fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
192 self.identifier.fmt(f)
193 }
194}
195
196impl FontTemplate {
200 pub fn new(
202 identifier: FontIdentifier,
203 descriptor: FontTemplateDescriptor,
204 font_face_rule: Option<ServoArc<FontFaceRuleInfo>>,
205 ) -> FontTemplate {
206 FontTemplate {
207 identifier,
208 descriptor,
209 font_face_rule,
210 }
211 }
212
213 pub fn new_for_local_web_font(
217 local_template: FontTemplateRef,
218 css_font_template_descriptors: &CSSFontFaceDescriptors,
219 font_face_rule: Option<ServoArc<FontFaceRuleInfo>>,
220 ) -> Result<FontTemplate, &'static str> {
221 let mut alias_template = local_template.borrow().clone();
222 alias_template
223 .descriptor
224 .override_values_with_css_font_template_descriptors(css_font_template_descriptors);
225 alias_template.font_face_rule = font_face_rule;
226 Ok(alias_template)
227 }
228
229 pub fn identifier(&self) -> &FontIdentifier {
230 &self.identifier
231 }
232
233 pub fn is_defined_by_font_face_rule(&self, rule: &ServoArc<FontFaceRuleInfo>) -> bool {
234 self.font_face_rule
235 .as_ref()
236 .is_some_and(|defining_rule| ServoArc::ptr_eq(rule, defining_rule))
237 }
238}
239
240pub trait FontTemplateRefMethods {
241 fn descriptor(&self) -> AtomicRef<'_, FontTemplateDescriptor>;
243 fn identifier(&self) -> AtomicRef<'_, FontIdentifier>;
245 fn matches_font_descriptor(&self, descriptor_to_match: &FontDescriptor) -> bool;
247 fn descriptor_distance(&self, descriptor_to_match: &FontDescriptor) -> f32;
250 fn char_in_unicode_range(&self, character: char) -> bool;
253
254 fn font_face_rule(&self) -> Option<AtomicRef<'_, ServoArc<FontFaceRuleInfo>>>;
256}
257
258impl FontTemplateRefMethods for FontTemplateRef {
259 fn descriptor(&self) -> AtomicRef<'_, FontTemplateDescriptor> {
260 AtomicRef::map(self.borrow(), |font_template_ref| {
261 &font_template_ref.descriptor
262 })
263 }
264
265 fn identifier(&self) -> AtomicRef<'_, FontIdentifier> {
266 AtomicRef::map(self.borrow(), |font_template_ref| {
267 &font_template_ref.identifier
268 })
269 }
270
271 fn matches_font_descriptor(&self, descriptor_to_match: &FontDescriptor) -> bool {
272 self.descriptor().matches(descriptor_to_match)
273 }
274
275 fn descriptor_distance(&self, descriptor_to_match: &FontDescriptor) -> f32 {
276 self.descriptor().distance_from(descriptor_to_match)
277 }
278
279 fn char_in_unicode_range(&self, character: char) -> bool {
280 let character = character as u32;
281 self.borrow()
282 .descriptor
283 .unicode_range
284 .as_ref()
285 .is_none_or(|ranges| ranges.iter().any(|range| range.contains(&character)))
286 }
287
288 fn font_face_rule(&self) -> Option<AtomicRef<'_, ServoArc<FontFaceRuleInfo>>> {
289 AtomicRef::filter_map(self.borrow(), |template| template.font_face_rule.as_ref())
290 }
291}
292
293trait FontMatchDistanceMethod<T>: Sized {
299 fn match_distance(&self, range: &T) -> f32;
300 fn to_float(&self) -> f32;
301}
302
303impl FontMatchDistanceMethod<ComputedFontWidthRange> for FontWidth {
304 fn match_distance(&self, range: &ComputedFontWidthRange) -> f32 {
305 const REVERSE_DISTANCE: f32 = 1000.0;
307
308 let min_width = range.0;
309 let max_width = range.1;
310
311 if *self < min_width {
317 if *self > FontWidth::NORMAL {
318 return min_width.to_float() - self.to_float();
319 }
320 return (min_width.to_float() - self.to_float()) + REVERSE_DISTANCE;
321 }
322
323 if *self > max_width {
324 if *self <= FontWidth::NORMAL {
325 return self.to_float() - max_width.to_float();
326 }
327 return (self.to_float() - max_width.to_float()) + REVERSE_DISTANCE;
328 }
329 0.0
330 }
331
332 fn to_float(&self) -> f32 {
333 self.0.to_float()
334 }
335}
336
337impl FontMatchDistanceMethod<ComputedFontWeightRange> for FontWeight {
338 fn match_distance(&self, range: &ComputedFontWeightRange) -> f32 {
350 const NOT_WITHIN_CENTRAL_RANGE: f32 = 100.0;
352 const REVERSE_DISTANCE: f32 = 600.0;
353
354 let min_weight = range.0;
355 let max_weight = range.1;
356
357 if *self >= min_weight && *self <= max_weight {
358 return 0.0;
360 }
361
362 if *self < FontWeight::NORMAL {
363 if max_weight < *self {
365 return self.to_float() - max_weight.to_float();
366 }
367
368 return (min_weight.to_float() - self.to_float()) + REVERSE_DISTANCE;
370 }
371
372 if *self > FontWeight::from_float(500.) {
373 if min_weight > *self {
375 return min_weight.to_float() - self.to_float();
376 }
377 return (self.to_float() - max_weight.to_float()) + REVERSE_DISTANCE;
379 }
380
381 if min_weight > *self {
383 if min_weight <= FontWeight::from_float(500.) {
384 return min_weight.to_float() - self.to_float();
386 }
387 return (min_weight.to_float() - self.to_float()) + REVERSE_DISTANCE;
389 }
390 (self.to_float() - max_weight.to_float()) + NOT_WITHIN_CENTRAL_RANGE
392 }
393
394 fn to_float(&self) -> f32 {
395 self.value()
396 }
397}
398
399impl FontMatchDistanceMethod<ComputedFontStyleRange> for FontStyle {
400 fn match_distance(&self, range: &ComputedFontStyleRange) -> f32 {
401 let min_style = range.0;
403 if *self == min_style {
404 return 0.0; }
406
407 const REVERSE: f32 = 100.0;
410
411 const NEGATE: f32 = 200.0;
414
415 if *self == FontStyle::NORMAL {
416 if min_style.is_oblique() {
417 let min_angle = min_style.oblique_degrees();
419 if min_angle >= 0.0 {
420 return 1.0 + min_angle;
421 }
422 let max_style = range.1;
423 let max_angle = max_style.oblique_degrees();
424 if max_angle >= 0.0 {
425 return 1.0;
427 }
428 return NEGATE - max_angle;
430 }
431 assert!(min_style == FontStyle::ITALIC);
434 return REVERSE;
435 }
436
437 let default_oblique_angle = FontStyle::OBLIQUE.oblique_degrees();
438 if *self == FontStyle::ITALIC {
439 if min_style.is_oblique() {
440 let min_angle = min_style.oblique_degrees();
441 if min_angle >= default_oblique_angle {
442 return 1.0 + (min_angle - default_oblique_angle);
443 }
444 let max_style = range.1;
445 let max_angle = max_style.oblique_degrees();
446 if max_angle >= default_oblique_angle {
447 return 1.0;
448 }
449 if max_angle > 0.0 {
450 return REVERSE + (default_oblique_angle - max_angle);
452 }
453 return REVERSE + NEGATE + (default_oblique_angle - max_angle);
455 }
456 assert!(min_style == FontStyle::NORMAL);
458 return NEGATE;
459 }
460
461 let target_angle = self.oblique_degrees();
465 if target_angle >= default_oblique_angle {
466 if min_style.is_oblique() {
467 let min_angle = min_style.oblique_degrees();
468 if min_angle >= target_angle {
469 return min_angle - target_angle;
470 }
471 let max_style = range.1;
472 let max_angle = max_style.oblique_degrees();
473 if max_angle >= target_angle {
474 return 0.0;
475 }
476 if max_angle > 0.0 {
477 return REVERSE + (target_angle - max_angle);
478 }
479 return REVERSE + NEGATE + (target_angle - max_angle);
480 }
481 if min_style == FontStyle::ITALIC {
482 return REVERSE + NEGATE;
483 }
484 return REVERSE + NEGATE + 1.0;
485 }
486
487 if target_angle <= -default_oblique_angle {
488 if min_style.is_oblique() {
489 let max_style = range.1;
490 let max_angle = max_style.oblique_degrees();
491 if max_angle <= target_angle {
492 return target_angle - max_angle;
493 }
494 let min_angle = min_style.oblique_degrees();
495 if min_angle <= target_angle {
496 return 0.0;
497 }
498 if min_angle < 0.0 {
499 return REVERSE + (min_angle - target_angle);
500 }
501 return REVERSE + NEGATE + (min_angle - target_angle);
502 }
503 if min_style == FontStyle::ITALIC {
504 return REVERSE + NEGATE;
505 }
506 return REVERSE + NEGATE + 1.0;
507 }
508
509 if target_angle >= 0.0 {
510 if min_style.is_oblique() {
511 let min_angle = min_style.oblique_degrees();
512 if min_angle > target_angle {
513 return REVERSE + (min_angle - target_angle);
514 }
515 let max_style = range.1;
516 let max_angle = max_style.oblique_degrees();
517 if max_angle >= target_angle {
518 return 0.0;
519 }
520 if max_angle > 0.0 {
521 return target_angle - max_angle;
522 }
523 return REVERSE + NEGATE + (target_angle - max_angle);
524 }
525 if min_style == FontStyle::ITALIC {
526 return REVERSE + NEGATE - 2.0;
527 }
528 return REVERSE + NEGATE - 1.0;
529 }
530
531 if min_style.is_oblique() {
533 let max_style = range.1;
534 let max_angle = max_style.oblique_degrees();
535 if max_angle < target_angle {
536 return REVERSE + (target_angle - max_angle);
537 }
538 let min_angle = min_style.oblique_degrees();
539 if min_angle <= target_angle {
540 return 0.0;
541 }
542 if min_angle < 0.0 {
543 return min_angle - target_angle;
544 }
545 return REVERSE + NEGATE + (min_angle - target_angle);
546 }
547 if min_style == FontStyle::ITALIC {
548 return REVERSE + NEGATE - 2.0;
549 }
550 REVERSE + NEGATE - 1.0
551 }
552
553 fn to_float(&self) -> f32 {
554 unimplemented!("Don't know how to convert FontStyle to float.");
555 }
556}
557
558pub trait IsOblique {
559 fn is_oblique(&self) -> bool;
560}
561
562impl IsOblique for FontStyle {
563 fn is_oblique(&self) -> bool {
564 *self != FontStyle::NORMAL && *self != FontStyle::ITALIC
565 }
566}