1use crate::Atom;
8use crate::derives::*;
9use crate::parser::{Parse, ParserContext};
10use crate::properties::CSSWideKeyword;
11use crate::typed_om::{ToTyped, TypedValue};
12use crate::values::animated::ToAnimatedValue;
13use crate::values::computed::{
14 Angle, Context, Integer, Length, NonNegativeLength, NonNegativeNumber, Number, Percentage,
15 ToComputedValue, Zoom,
16};
17use crate::values::generics::font::{
18 FeatureTagValue, FontSettings, TaggedFontValue, VariationValue,
19};
20use crate::values::generics::{NonNegative, font as generics};
21use crate::values::resolved::{Context as ResolvedContext, ToResolvedValue};
22use crate::values::specified::font::{
23 self as specified, KeywordInfo, MAX_FONT_WEIGHT, MIN_FONT_WEIGHT,
24};
25use crate::values::specified::length::{FontBaseSize, LineHeightBase};
26use crate::values::{CSSInteger, StyleParseErrorKind};
27use cssparser::{CssStringWriter, Parser, serialize_identifier};
28use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
29use num_traits::abs;
30use num_traits::cast::AsPrimitive;
31use std::fmt::{self, Write};
32use style_traits::{CssWriter, ParseError, ToCss};
33use thin_vec::ThinVec;
34
35pub use crate::values::computed::Length as MozScriptMinSize;
36pub use crate::values::specified::Integer as SpecifiedInteger;
37pub use crate::values::specified::Number as SpecifiedNumber;
38pub use crate::values::specified::font::{
39 FontKerning, FontOpticalSizing, FontPalette, FontSmoothing, FontSynthesis, FontSynthesisStyle,
40 FontVariantCaps, FontVariantEmoji, FontVariantPosition, MathShift, MathStyle, MathVariant,
41 MozScriptSizeMultiplier,
42};
43pub use crate::values::specified::font::{
44 FontVariantAlternates, FontVariantEastAsian, FontVariantLigatures, FontVariantNumeric,
45 QueryFontMetricsFlags, XLang, XTextScale,
46};
47
48#[repr(C)]
67#[derive(
68 Clone,
69 ComputeSquaredDistance,
70 Copy,
71 Debug,
72 Deserialize,
73 Eq,
74 Hash,
75 MallocSizeOf,
76 PartialEq,
77 PartialOrd,
78 Serialize,
79 ToResolvedValue,
80)]
81pub struct FixedPoint<T, const FRACTION_BITS: u16> {
82 pub value: T,
84}
85
86impl<T, const FRACTION_BITS: u16> FixedPoint<T, FRACTION_BITS>
87where
88 T: AsPrimitive<f32>,
89 f32: AsPrimitive<T>,
90 u16: AsPrimitive<T>,
91{
92 const SCALE: u16 = 1 << FRACTION_BITS;
93 const INVERSE_SCALE: f32 = 1.0 / Self::SCALE as f32;
94
95 pub fn from_float(v: f32) -> Self {
97 Self {
98 value: (v * Self::SCALE as f32).round().as_(),
99 }
100 }
101
102 pub fn to_float(&self) -> f32 {
104 self.value.as_() * Self::INVERSE_SCALE
105 }
106}
107
108impl<const FRACTION_BITS: u16> std::ops::Div for FixedPoint<u16, FRACTION_BITS> {
111 type Output = Self;
112 fn div(self, rhs: Self) -> Self {
113 Self {
114 value: (((self.value as u32) << (FRACTION_BITS as u32)) / (rhs.value as u32)) as u16,
115 }
116 }
117}
118impl<const FRACTION_BITS: u16> std::ops::Mul for FixedPoint<u16, FRACTION_BITS> {
119 type Output = Self;
120 fn mul(self, rhs: Self) -> Self {
121 Self {
122 value: (((self.value as u32) * (rhs.value as u32)) >> (FRACTION_BITS as u32)) as u16,
123 }
124 }
125}
126
127pub const FONT_WEIGHT_FRACTION_BITS: u16 = 6;
132
133pub type FontWeightFixedPoint = FixedPoint<u16, FONT_WEIGHT_FRACTION_BITS>;
136
137#[derive(
146 Clone,
147 ComputeSquaredDistance,
148 Copy,
149 Debug,
150 Deserialize,
151 Hash,
152 MallocSizeOf,
153 PartialEq,
154 PartialOrd,
155 Serialize,
156 ToResolvedValue,
157)]
158#[repr(C)]
159pub struct FontWeight(FontWeightFixedPoint);
160impl ToAnimatedValue for FontWeight {
161 type AnimatedValue = Number;
162
163 #[inline]
164 fn to_animated_value(self, _: &crate::values::animated::Context) -> Self::AnimatedValue {
165 self.value()
166 }
167
168 #[inline]
169 fn from_animated_value(animated: Self::AnimatedValue) -> Self {
170 FontWeight::from_float(animated)
171 }
172}
173
174impl ToCss for FontWeight {
175 fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
176 where
177 W: fmt::Write,
178 {
179 self.value().to_css(dest)
180 }
181}
182
183impl ToTyped for FontWeight {
184 fn to_typed(&self, dest: &mut ThinVec<TypedValue>) -> Result<(), ()> {
185 self.value().to_typed(dest)
186 }
187}
188
189impl FontWeight {
190 pub const NORMAL: FontWeight = FontWeight(FontWeightFixedPoint {
192 value: 400 << FONT_WEIGHT_FRACTION_BITS,
193 });
194
195 pub const BOLD: FontWeight = FontWeight(FontWeightFixedPoint {
197 value: 700 << FONT_WEIGHT_FRACTION_BITS,
198 });
199
200 pub const BOLD_THRESHOLD: FontWeight = FontWeight(FontWeightFixedPoint {
202 value: 600 << FONT_WEIGHT_FRACTION_BITS,
203 });
204
205 pub const PREFER_BOLD_THRESHOLD: FontWeight = FontWeight(FontWeightFixedPoint {
208 value: 500 << FONT_WEIGHT_FRACTION_BITS,
209 });
210
211 pub fn normal() -> Self {
213 Self::NORMAL
214 }
215
216 pub fn is_bold(&self) -> bool {
218 *self >= Self::BOLD_THRESHOLD
219 }
220
221 pub fn value(&self) -> f32 {
223 self.0.to_float()
224 }
225
226 pub fn from_float(v: f32) -> Self {
228 Self(FixedPoint::from_float(
229 v.max(MIN_FONT_WEIGHT).min(MAX_FONT_WEIGHT),
230 ))
231 }
232
233 pub fn bolder(self) -> Self {
238 let value = self.value();
239 if value < 350. {
240 return Self::NORMAL;
241 }
242 if value < 550. {
243 return Self::BOLD;
244 }
245 Self::from_float(value.max(900.))
246 }
247
248 pub fn lighter(self) -> Self {
253 let value = self.value();
254 if value < 550. {
255 return Self::from_float(value.min(100.));
256 }
257 if value < 750. {
258 return Self::NORMAL;
259 }
260 Self::BOLD
261 }
262}
263
264#[derive(
265 Animate,
266 Clone,
267 ComputeSquaredDistance,
268 Copy,
269 Debug,
270 Deserialize,
271 MallocSizeOf,
272 PartialEq,
273 Serialize,
274 ToAnimatedZero,
275 ToCss,
276 ToTyped,
277)]
278pub struct FontSize {
280 pub computed_size: NonNegativeLength,
283 #[css(skip)]
286 pub used_size: NonNegativeLength,
287 #[css(skip)]
289 pub keyword_info: KeywordInfo,
290}
291
292impl FontSize {
293 #[inline]
295 pub fn computed_size(&self) -> Length {
296 self.computed_size.0
297 }
298
299 #[inline]
301 pub fn used_size(&self) -> Length {
302 self.used_size.0
303 }
304
305 #[inline]
307 pub fn zoom(&self, zoom: Zoom) -> Self {
308 Self {
309 computed_size: NonNegative(Length::new(zoom.zoom(self.computed_size.0.px()))),
310 used_size: NonNegative(Length::new(zoom.zoom(self.used_size.0.px()))),
311 keyword_info: self.keyword_info,
312 }
313 }
314
315 #[inline]
316 pub fn medium() -> Self {
318 Self {
319 computed_size: NonNegative(Length::new(specified::FONT_MEDIUM_PX)),
320 used_size: NonNegative(Length::new(specified::FONT_MEDIUM_PX)),
321 keyword_info: KeywordInfo::medium(),
322 }
323 }
324}
325
326impl ToAnimatedValue for FontSize {
327 type AnimatedValue = Length;
328
329 #[inline]
330 fn to_animated_value(self, context: &crate::values::animated::Context) -> Self::AnimatedValue {
331 self.computed_size.0.to_animated_value(context)
332 }
333
334 #[inline]
335 fn from_animated_value(animated: Self::AnimatedValue) -> Self {
336 FontSize {
337 computed_size: NonNegative(animated.clamp_to_non_negative()),
338 used_size: NonNegative(animated.clamp_to_non_negative()),
339 keyword_info: KeywordInfo::none(),
340 }
341 }
342}
343
344impl ToResolvedValue for FontSize {
345 type ResolvedValue = NonNegativeLength;
346
347 #[inline]
348 fn to_resolved_value(self, context: &ResolvedContext) -> Self::ResolvedValue {
349 self.computed_size.to_resolved_value(context)
350 }
351
352 #[inline]
353 fn from_resolved_value(resolved: Self::ResolvedValue) -> Self {
354 let computed_size = NonNegativeLength::from_resolved_value(resolved);
355 Self {
356 computed_size,
357 used_size: computed_size,
358 keyword_info: KeywordInfo::none(),
359 }
360 }
361}
362
363#[derive(
364 Clone,
365 Debug,
366 Deserialize,
367 Eq,
368 Hash,
369 PartialEq,
370 Serialize,
371 ToComputedValue,
372 ToResolvedValue,
373 ToTyped,
374)]
375#[repr(C)]
377#[typed(todo_derive_fields)]
378pub struct FontFamily {
379 pub families: FontFamilyList,
381 pub is_system_font: bool,
383 pub is_initial: bool,
386}
387
388macro_rules! static_font_family {
389 ($ident:ident, $family:expr) => {
390 static $ident: std::sync::LazyLock<FontFamily> = std::sync::LazyLock::new(|| FontFamily {
391 families: FontFamilyList {
392 list: crate::ArcSlice::from_iter_leaked(std::iter::once($family)),
393 },
394 is_system_font: false,
395 is_initial: false,
396 });
397 };
398}
399
400impl FontFamily {
401 #[inline]
402 pub fn serif() -> Self {
404 Self::generic(GenericFontFamily::Serif).clone()
405 }
406
407 #[cfg(feature = "gecko")]
409 pub(crate) fn moz_bullet() -> &'static Self {
410 static_font_family!(
411 MOZ_BULLET,
412 SingleFontFamily::FamilyName(FamilyName {
413 name: atom!("-moz-bullet-font"),
414 syntax: FontFamilyNameSyntax::Identifiers,
415 })
416 );
417
418 &MOZ_BULLET
419 }
420
421 #[cfg(feature = "gecko")]
423 pub fn for_system_font(name: &str) -> Self {
424 Self {
425 families: FontFamilyList {
426 list: crate::ArcSlice::from_iter(std::iter::once(SingleFontFamily::FamilyName(
427 FamilyName {
428 name: Atom::from(name),
429 syntax: FontFamilyNameSyntax::Identifiers,
430 },
431 ))),
432 },
433 is_system_font: true,
434 is_initial: false,
435 }
436 }
437
438 pub fn generic(generic: GenericFontFamily) -> &'static Self {
440 macro_rules! generic_font_family {
441 ($ident:ident, $family:ident) => {
442 static_font_family!(
443 $ident,
444 SingleFontFamily::Generic(GenericFontFamily::$family)
445 )
446 };
447 }
448
449 generic_font_family!(SERIF, Serif);
450 generic_font_family!(SANS_SERIF, SansSerif);
451 generic_font_family!(MONOSPACE, Monospace);
452 generic_font_family!(CURSIVE, Cursive);
453 generic_font_family!(FANTASY, Fantasy);
454 #[cfg(feature = "gecko")]
455 generic_font_family!(MATH, Math);
456 #[cfg(feature = "gecko")]
457 generic_font_family!(MOZ_EMOJI, MozEmoji);
458 generic_font_family!(SYSTEM_UI, SystemUi);
459
460 let family = match generic {
461 GenericFontFamily::None => {
462 debug_assert!(false, "Bogus caller!");
463 &*SERIF
464 },
465 GenericFontFamily::Serif => &*SERIF,
466 GenericFontFamily::SansSerif => &*SANS_SERIF,
467 GenericFontFamily::Monospace => &*MONOSPACE,
468 GenericFontFamily::Cursive => &*CURSIVE,
469 GenericFontFamily::Fantasy => &*FANTASY,
470 #[cfg(feature = "gecko")]
471 GenericFontFamily::Math => &*MATH,
472 #[cfg(feature = "gecko")]
473 GenericFontFamily::MozEmoji => &*MOZ_EMOJI,
474 GenericFontFamily::SystemUi => &*SYSTEM_UI,
475 };
476 debug_assert_eq!(
477 *family.families.iter().next().unwrap(),
478 SingleFontFamily::Generic(generic)
479 );
480 family
481 }
482}
483
484impl MallocSizeOf for FontFamily {
485 fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
486 use malloc_size_of::MallocUnconditionalSizeOf;
487 let shared_font_list = &self.families.list;
491 if shared_font_list.is_unique() {
492 shared_font_list.unconditional_size_of(ops)
493 } else {
494 0
495 }
496 }
497}
498
499impl ToCss for FontFamily {
500 fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
501 where
502 W: fmt::Write,
503 {
504 let mut iter = self.families.iter();
505 match iter.next() {
506 Some(f) => f.to_css(dest)?,
507 None => return Ok(()),
508 }
509 for family in iter {
510 dest.write_str(", ")?;
511 family.to_css(dest)?;
512 }
513 Ok(())
514 }
515}
516
517#[derive(
519 Clone,
520 Debug,
521 Deserialize,
522 Eq,
523 Hash,
524 MallocSizeOf,
525 PartialEq,
526 Serialize,
527 ToComputedValue,
528 ToResolvedValue,
529 ToShmem,
530)]
531#[repr(C)]
532pub struct FamilyName {
533 pub name: Atom,
535 pub syntax: FontFamilyNameSyntax,
537}
538
539#[cfg(feature = "gecko")]
540impl FamilyName {
541 fn is_known_icon_font_family(&self) -> bool {
542 use crate::gecko_bindings::bindings;
543 unsafe { bindings::Gecko_IsKnownIconFontFamily(self.name.as_ptr()) }
544 }
545}
546
547#[cfg(feature = "servo")]
548impl FamilyName {
549 fn is_known_icon_font_family(&self) -> bool {
550 false
551 }
552}
553
554impl ToCss for FamilyName {
555 fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
556 where
557 W: fmt::Write,
558 {
559 match self.syntax {
560 FontFamilyNameSyntax::Quoted => {
561 dest.write_char('"')?;
562 write!(CssStringWriter::new(dest), "{}", self.name)?;
563 dest.write_char('"')
564 },
565 FontFamilyNameSyntax::Identifiers => {
566 let mut first = true;
567 for ident in self.name.to_string().split(' ') {
568 if first {
569 first = false;
570 } else {
571 dest.write_char(' ')?;
572 }
573 debug_assert!(
574 !ident.is_empty(),
575 "Family name with leading, \
576 trailing, or consecutive white spaces should \
577 have been marked quoted by the parser"
578 );
579 serialize_identifier(ident, dest)?;
580 }
581 Ok(())
582 },
583 }
584 }
585}
586
587#[derive(
588 Clone,
589 Copy,
590 Debug,
591 Deserialize,
592 Eq,
593 Hash,
594 MallocSizeOf,
595 PartialEq,
596 Serialize,
597 ToComputedValue,
598 ToResolvedValue,
599 ToShmem,
600)]
601#[repr(u8)]
604pub enum FontFamilyNameSyntax {
605 Quoted,
608
609 Identifiers,
612}
613
614#[derive(
617 Clone,
618 Debug,
619 Deserialize,
620 Eq,
621 Hash,
622 MallocSizeOf,
623 PartialEq,
624 Serialize,
625 ToCss,
626 ToComputedValue,
627 ToResolvedValue,
628 ToShmem,
629)]
630#[repr(u8)]
631pub enum SingleFontFamily {
632 FamilyName(FamilyName),
634 Generic(GenericFontFamily),
636}
637
638fn system_ui_enabled(_: &ParserContext) -> bool {
639 crate::pref!("layout.css.system-ui.enabled")
640}
641
642#[derive(
652 Clone,
653 Copy,
654 Debug,
655 Deserialize,
656 Eq,
657 Hash,
658 MallocSizeOf,
659 PartialEq,
660 Parse,
661 Serialize,
662 ToCss,
663 ToComputedValue,
664 ToResolvedValue,
665 ToShmem,
666)]
667#[repr(u32)]
668#[allow(missing_docs)]
669pub enum GenericFontFamily {
670 #[css(skip)]
674 None = 0,
675 Serif,
676 SansSerif,
677 #[parse(aliases = "-moz-fixed")]
678 Monospace,
679 Cursive,
680 Fantasy,
681 #[cfg(feature = "gecko")]
682 Math,
683 #[parse(condition = "system_ui_enabled")]
684 SystemUi,
685 #[css(skip)]
687 #[cfg(feature = "gecko")]
688 MozEmoji,
689}
690
691impl GenericFontFamily {
692 pub(crate) fn valid_for_user_font_prioritization(self) -> bool {
696 match self {
697 Self::None | Self::Cursive | Self::Fantasy | Self::SystemUi => false,
698 #[cfg(feature = "gecko")]
699 Self::Math | Self::MozEmoji => false,
700 Self::Serif | Self::SansSerif | Self::Monospace => true,
701 }
702 }
703}
704
705impl Parse for SingleFontFamily {
706 fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
708 let is_reserved_kw = |s: &str| -> bool {
712 CSSWideKeyword::from_ident(s).is_ok() || s.eq_ignore_ascii_case("default")
713 };
714
715 let canonical_syntax_for = |s: &str| -> FontFamilyNameSyntax {
718 let mut in_word = false;
724 for b in s.as_bytes() {
725 if in_word && *b == b' ' {
726 in_word = false;
727 continue;
728 }
729 if !in_word && b.is_ascii_digit() {
730 return FontFamilyNameSyntax::Quoted;
731 }
732 if b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_' || !b.is_ascii() {
733 in_word = true;
734 continue;
735 }
736 return FontFamilyNameSyntax::Quoted;
737 }
738 if !in_word {
739 return FontFamilyNameSyntax::Quoted;
740 }
741 if is_reserved_kw(s) {
743 return FontFamilyNameSyntax::Quoted;
744 }
745 if GenericFontFamily::parse(context, &mut Parser::new(&s)).is_ok() {
747 return FontFamilyNameSyntax::Quoted;
748 }
749 FontFamilyNameSyntax::Identifiers
750 };
751
752 if let Ok(value) = input.try_parse(|i| i.expect_string_cloned()) {
753 return Ok(SingleFontFamily::FamilyName(FamilyName {
754 name: Atom::from(&*value),
755 syntax: canonical_syntax_for(&value),
756 }));
757 }
758
759 if let Ok(generic) = input.try_parse(|i| GenericFontFamily::parse(context, i)) {
760 return Ok(SingleFontFamily::Generic(generic));
761 }
762
763 let first_ident = input.expect_ident_cloned()?;
764 let mut value = first_ident.as_ref().to_owned();
765 while let Ok(ident) = input.try_parse(|i| i.expect_ident_cloned()) {
766 value.push(' ');
767 value.push_str(&ident);
768 }
769
770 if is_reserved_kw(&value) {
771 return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
772 }
773
774 Ok(SingleFontFamily::FamilyName(FamilyName {
775 name: Atom::from(&*value),
776 syntax: canonical_syntax_for(&value),
777 }))
778 }
779}
780
781#[derive(
783 Clone,
784 Debug,
785 Deserialize,
786 Hash,
787 Serialize,
788 ToComputedValue,
789 ToResolvedValue,
790 ToShmem,
791 PartialEq,
792 Eq,
793)]
794#[repr(C)]
795pub struct FontFamilyList {
796 pub list: crate::ArcSlice<SingleFontFamily>,
798}
799
800impl FontFamilyList {
801 pub fn iter(&self) -> impl Iterator<Item = &SingleFontFamily> {
803 self.list.iter()
804 }
805
806 #[cfg_attr(feature = "servo", allow(unused))]
813 pub(crate) fn prioritize_first_generic_or_prepend(&mut self, generic: GenericFontFamily) {
814 let mut index_of_first_generic = None;
815 let mut target_index = None;
816
817 for (i, f) in self.iter().enumerate() {
818 match f {
819 SingleFontFamily::Generic(f) => {
820 if index_of_first_generic.is_none() && f.valid_for_user_font_prioritization() {
821 if target_index.is_none() {
825 return;
826 }
827 index_of_first_generic = Some(i);
828 break;
829 }
830 if target_index.is_none() {
833 target_index = Some(i);
834 }
835 },
836 SingleFontFamily::FamilyName(fam) => {
837 if target_index.is_none() && !fam.is_known_icon_font_family() {
840 target_index = Some(i);
841 }
842 },
843 }
844 }
845
846 let mut new_list = self.list.iter().cloned().collect::<Vec<_>>();
847 let first_generic = match index_of_first_generic {
848 Some(i) => new_list.remove(i),
849 None => SingleFontFamily::Generic(generic),
850 };
851
852 if let Some(i) = target_index {
853 new_list.insert(i, first_generic);
854 } else {
855 new_list.push(first_generic);
856 }
857 self.list = crate::ArcSlice::from_iter(new_list.into_iter());
858 }
859
860 #[cfg_attr(feature = "servo", allow(unused))]
862 pub(crate) fn needs_user_font_prioritization(&self) -> bool {
863 self.iter().next().is_none_or(|f| match f {
864 SingleFontFamily::Generic(f) => !f.valid_for_user_font_prioritization(),
865 _ => true,
866 })
867 }
868
869 pub fn single_generic(&self) -> Option<GenericFontFamily> {
871 let mut iter = self.iter();
872 if let Some(SingleFontFamily::Generic(f)) = iter.next()
873 && iter.next().is_none()
874 {
875 return Some(*f);
876 }
877 None
878 }
879}
880
881pub type FontSizeAdjust = generics::GenericFontSizeAdjust<NonNegativeNumber>;
883
884impl FontSizeAdjust {
885 #[inline]
886 pub fn none() -> Self {
888 FontSizeAdjust::None
889 }
890}
891
892impl ToComputedValue for specified::FontSizeAdjust {
893 type ComputedValue = FontSizeAdjust;
894
895 fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
896 use crate::font_metrics::FontMetricsOrientation;
897
898 let font_metrics = |vertical, flags| {
899 let orient = if vertical {
900 FontMetricsOrientation::MatchContextPreferVertical
901 } else {
902 FontMetricsOrientation::Horizontal
903 };
904 let metrics = context.query_font_metrics(FontBaseSize::CurrentStyle, orient, flags);
905 let font_size = context
906 .style()
907 .get_font()
908 .slow_clone_font_size()
909 .used_size
910 .0;
911 (metrics, font_size)
912 };
913
914 macro_rules! resolve {
918 ($basis:ident, $value:expr, $vertical:expr, $field:ident, $fallback:expr, $flags:expr) => {{
919 match $value {
920 specified::FontSizeAdjustFactor::Number(f) => {
921 FontSizeAdjust::$basis(f.to_computed_value(context))
922 },
923 specified::FontSizeAdjustFactor::FromFont => {
924 let (metrics, font_size) = font_metrics($vertical, $flags);
925 let ratio = if let Some(metric) = metrics.$field {
926 metric / font_size
927 } else if $fallback >= 0.0 {
928 $fallback
929 } else {
930 metrics.ascent / font_size
931 };
932 if ratio.is_nan() {
933 FontSizeAdjust::$basis(NonNegative(abs($fallback)))
934 } else {
935 FontSizeAdjust::$basis(NonNegative(ratio))
936 }
937 },
938 }
939 }};
940 }
941
942 match self {
943 Self::None => FontSizeAdjust::None,
944 Self::ExHeight(val) => {
945 resolve!(
946 ExHeight,
947 val,
948 false,
949 x_height,
950 0.5,
951 QueryFontMetricsFlags::empty()
952 )
953 },
954 Self::CapHeight(val) => {
955 resolve!(
956 CapHeight,
957 val,
958 false,
959 cap_height,
960 -1.0, QueryFontMetricsFlags::empty()
962 )
963 },
964 Self::ChWidth(val) => {
965 resolve!(
966 ChWidth,
967 val,
968 false,
969 zero_advance_measure,
970 0.5,
971 QueryFontMetricsFlags::NEEDS_CH
972 )
973 },
974 Self::IcWidth(val) => {
975 resolve!(
976 IcWidth,
977 val,
978 false,
979 ic_width,
980 1.0,
981 QueryFontMetricsFlags::NEEDS_IC
982 )
983 },
984 Self::IcHeight(val) => {
985 resolve!(
986 IcHeight,
987 val,
988 true,
989 ic_width,
990 1.0,
991 QueryFontMetricsFlags::NEEDS_IC
992 )
993 },
994 }
995 }
996
997 fn from_computed_value(computed: &Self::ComputedValue) -> Self {
998 macro_rules! case {
999 ($basis:ident, $val:expr) => {
1000 Self::$basis(specified::FontSizeAdjustFactor::Number(
1001 ToComputedValue::from_computed_value($val),
1002 ))
1003 };
1004 }
1005 match *computed {
1006 FontSizeAdjust::None => Self::None,
1007 FontSizeAdjust::ExHeight(ref val) => case!(ExHeight, val),
1008 FontSizeAdjust::CapHeight(ref val) => case!(CapHeight, val),
1009 FontSizeAdjust::ChWidth(ref val) => case!(ChWidth, val),
1010 FontSizeAdjust::IcWidth(ref val) => case!(IcWidth, val),
1011 FontSizeAdjust::IcHeight(ref val) => case!(IcHeight, val),
1012 }
1013 }
1014}
1015
1016pub type FontFeatureSettings = FontSettings<FeatureTagValue<Integer>>;
1018
1019pub type FontVariationSettings = FontSettings<VariationValue<Number>>;
1021
1022fn dedup_font_settings<T>(settings_list: &mut ThinVec<T>)
1025where
1026 T: TaggedFontValue,
1027{
1028 if settings_list.len() > 1 {
1029 settings_list.sort_by_key(|k| k.tag().0);
1030 settings_list.dedup_by(|a, b| {
1033 if a.tag() == b.tag() {
1034 std::mem::swap(a, b);
1035 true
1036 } else {
1037 false
1038 }
1039 });
1040 }
1041}
1042
1043impl<T> ToComputedValue for FontSettings<T>
1044where
1045 T: ToComputedValue,
1046 <T as ToComputedValue>::ComputedValue: TaggedFontValue,
1047{
1048 type ComputedValue = FontSettings<T::ComputedValue>;
1049
1050 fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
1051 let mut v = self
1052 .0
1053 .iter()
1054 .map(|item| item.to_computed_value(context))
1055 .collect::<ThinVec<_>>();
1056 dedup_font_settings(&mut v);
1057 FontSettings(v)
1058 }
1059
1060 fn from_computed_value(computed: &Self::ComputedValue) -> Self {
1061 Self(computed.0.iter().map(T::from_computed_value).collect())
1062 }
1063}
1064
1065#[derive(
1070 Clone,
1071 Copy,
1072 Debug,
1073 Deserialize,
1074 Eq,
1075 MallocSizeOf,
1076 PartialEq,
1077 Serialize,
1078 SpecifiedValueInfo,
1079 ToComputedValue,
1080 ToResolvedValue,
1081 ToShmem,
1082 ToTyped,
1083)]
1084#[repr(C)]
1085#[typed(todo_derive_fields)]
1086#[value_info(other_values = "normal")]
1087pub struct FontLanguageOverride(pub u32);
1088
1089impl FontLanguageOverride {
1090 #[inline]
1091 pub fn normal() -> FontLanguageOverride {
1093 FontLanguageOverride(0)
1094 }
1095
1096 #[inline]
1098 pub(crate) fn to_str(self, storage: &mut [u8; 4]) -> &str {
1099 *storage = u32::to_be_bytes(self.0);
1100 let slice = if cfg!(debug_assertions) {
1102 std::str::from_utf8(&storage[..]).unwrap()
1103 } else {
1104 unsafe { std::str::from_utf8_unchecked(&storage[..]) }
1105 };
1106 slice.trim_end()
1107 }
1108
1109 #[inline]
1112 pub unsafe fn from_u32(value: u32) -> Self {
1113 Self(value)
1114 }
1115}
1116
1117impl ToCss for FontLanguageOverride {
1118 fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
1119 where
1120 W: fmt::Write,
1121 {
1122 if self.0 == 0 {
1123 return dest.write_str("normal");
1124 }
1125 self.to_str(&mut [0; 4]).to_css(dest)
1126 }
1127}
1128
1129impl ToComputedValue for specified::MozScriptMinSize {
1130 type ComputedValue = MozScriptMinSize;
1131
1132 fn to_computed_value(&self, cx: &Context) -> MozScriptMinSize {
1133 let base_size = FontBaseSize::InheritedStyle;
1136 let line_height_base = LineHeightBase::InheritedStyle;
1137 self.0
1138 .to_computed_value_with_base_size(cx, base_size, line_height_base)
1139 }
1140
1141 fn from_computed_value(other: &MozScriptMinSize) -> Self {
1142 specified::MozScriptMinSize(ToComputedValue::from_computed_value(other))
1143 }
1144}
1145
1146pub type MathDepth = i8;
1148
1149impl ToComputedValue for specified::MathDepth {
1150 type ComputedValue = MathDepth;
1151
1152 fn to_computed_value(&self, cx: &Context) -> i8 {
1153 use crate::properties::longhands::math_style::SpecifiedValue as MathStyleValue;
1154
1155 let int = match self {
1156 specified::MathDepth::AutoAdd => {
1157 let parent = *cx.builder.get_parent_font().get_math_depth() as i32;
1158 let style = *cx.builder.get_parent_font().get_math_style();
1159 if style == MathStyleValue::Compact {
1160 parent.saturating_add(1)
1161 } else {
1162 parent
1163 }
1164 },
1165 specified::MathDepth::Add(rel) => {
1166 let parent = *cx.builder.get_parent_font().get_math_depth();
1167 (parent as i32).saturating_add(rel.to_computed_value(cx))
1168 },
1169 specified::MathDepth::Absolute(abs) => abs.to_computed_value(cx),
1170 };
1171 std::cmp::min(int, i8::MAX as i32) as i8
1172 }
1173
1174 fn from_computed_value(other: &i8) -> Self {
1175 let computed_value = *other as i32;
1176 specified::MathDepth::Absolute(SpecifiedInteger::from_computed_value(&computed_value))
1177 }
1178}
1179
1180impl ToAnimatedValue for MathDepth {
1181 type AnimatedValue = CSSInteger;
1182
1183 #[inline]
1184 fn to_animated_value(self, _: &crate::values::animated::Context) -> Self::AnimatedValue {
1185 self.into()
1186 }
1187
1188 #[inline]
1189 fn from_animated_value(animated: Self::AnimatedValue) -> Self {
1190 std::cmp::min(animated, i8::MAX as i32) as i8
1191 }
1192}
1193
1194pub const FONT_STYLE_FRACTION_BITS: u16 = 8;
1199
1200pub type FontStyleFixedPoint = FixedPoint<i16, FONT_STYLE_FRACTION_BITS>;
1203
1204#[derive(
1215 Clone,
1216 ComputeSquaredDistance,
1217 Copy,
1218 Debug,
1219 Deserialize,
1220 Eq,
1221 Hash,
1222 MallocSizeOf,
1223 PartialEq,
1224 PartialOrd,
1225 Serialize,
1226 ToResolvedValue,
1227 ToTyped,
1228)]
1229#[repr(C)]
1230#[typed(todo_derive_fields)]
1231pub struct FontStyle(FontStyleFixedPoint);
1232
1233impl FontStyle {
1234 pub const NORMAL: FontStyle = FontStyle(FontStyleFixedPoint {
1236 value: 0 << FONT_STYLE_FRACTION_BITS,
1237 });
1238
1239 pub const ITALIC: FontStyle = FontStyle(FontStyleFixedPoint {
1241 value: 100 << FONT_STYLE_FRACTION_BITS,
1242 });
1243
1244 pub const DEFAULT_OBLIQUE_DEGREES: i16 = 14;
1247
1248 pub const OBLIQUE: FontStyle = FontStyle(FontStyleFixedPoint {
1250 value: Self::DEFAULT_OBLIQUE_DEGREES << FONT_STYLE_FRACTION_BITS,
1251 });
1252
1253 #[inline]
1255 pub fn normal() -> Self {
1256 Self::NORMAL
1257 }
1258
1259 pub fn oblique(degrees: f32) -> Self {
1261 Self(FixedPoint::from_float(
1262 degrees
1263 .max(specified::FONT_STYLE_OBLIQUE_MIN_ANGLE_DEGREES)
1264 .min(specified::FONT_STYLE_OBLIQUE_MAX_ANGLE_DEGREES),
1265 ))
1266 }
1267
1268 pub fn oblique_degrees(&self) -> f32 {
1270 debug_assert_ne!(*self, Self::ITALIC);
1271 self.0.to_float()
1272 }
1273}
1274
1275impl ToCss for FontStyle {
1276 fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
1277 where
1278 W: fmt::Write,
1279 {
1280 if *self == Self::NORMAL {
1281 return dest.write_str("normal");
1282 }
1283 if *self == Self::ITALIC {
1284 return dest.write_str("italic");
1285 }
1286 dest.write_str("oblique")?;
1287 if *self != Self::OBLIQUE {
1288 dest.write_char(' ')?;
1290 Angle::from_degrees(self.oblique_degrees()).to_css(dest)?;
1291 }
1292 Ok(())
1293 }
1294}
1295
1296impl ToAnimatedValue for FontStyle {
1297 type AnimatedValue = generics::FontStyle<Angle>;
1298
1299 #[inline]
1300 fn to_animated_value(self, _: &crate::values::animated::Context) -> Self::AnimatedValue {
1301 if self == Self::ITALIC {
1302 return generics::FontStyle::Italic;
1303 }
1304 generics::FontStyle::Oblique(Angle::from_degrees(self.oblique_degrees()))
1305 }
1306
1307 #[inline]
1308 fn from_animated_value(animated: Self::AnimatedValue) -> Self {
1309 match animated {
1310 generics::FontStyle::Italic => Self::ITALIC,
1311 generics::FontStyle::Oblique(ref angle) => Self::oblique(angle.degrees()),
1312 }
1313 }
1314}
1315
1316pub const FONT_WIDTH_FRACTION_BITS: u16 = 6;
1323
1324pub type FontWidthFixedPoint = FixedPoint<u16, FONT_WIDTH_FRACTION_BITS>;
1327
1328#[derive(
1339 Clone,
1340 ComputeSquaredDistance,
1341 Copy,
1342 Debug,
1343 Deserialize,
1344 Hash,
1345 MallocSizeOf,
1346 PartialEq,
1347 PartialOrd,
1348 Serialize,
1349 ToResolvedValue,
1350)]
1351#[repr(C)]
1352pub struct FontWidth(pub FontWidthFixedPoint);
1353
1354impl FontWidth {
1355 pub const FRACTION_BITS: u16 = FONT_WIDTH_FRACTION_BITS;
1357 pub const HALF: u16 = 1 << (Self::FRACTION_BITS - 1);
1359
1360 pub const ULTRA_CONDENSED: FontWidth = FontWidth(FontWidthFixedPoint {
1362 value: 50 << Self::FRACTION_BITS,
1363 });
1364 pub const EXTRA_CONDENSED: FontWidth = FontWidth(FontWidthFixedPoint {
1366 value: (62 << Self::FRACTION_BITS) + Self::HALF,
1367 });
1368 pub const CONDENSED: FontWidth = FontWidth(FontWidthFixedPoint {
1370 value: 75 << Self::FRACTION_BITS,
1371 });
1372 pub const SEMI_CONDENSED: FontWidth = FontWidth(FontWidthFixedPoint {
1374 value: (87 << Self::FRACTION_BITS) + Self::HALF,
1375 });
1376 pub const NORMAL: FontWidth = FontWidth(FontWidthFixedPoint {
1378 value: 100 << Self::FRACTION_BITS,
1379 });
1380 pub const SEMI_EXPANDED: FontWidth = FontWidth(FontWidthFixedPoint {
1382 value: (112 << Self::FRACTION_BITS) + Self::HALF,
1383 });
1384 pub const EXPANDED: FontWidth = FontWidth(FontWidthFixedPoint {
1386 value: 125 << Self::FRACTION_BITS,
1387 });
1388 pub const EXTRA_EXPANDED: FontWidth = FontWidth(FontWidthFixedPoint {
1390 value: 150 << Self::FRACTION_BITS,
1391 });
1392 pub const ULTRA_EXPANDED: FontWidth = FontWidth(FontWidthFixedPoint {
1394 value: 200 << Self::FRACTION_BITS,
1395 });
1396
1397 pub fn hundred() -> Self {
1399 Self::NORMAL
1400 }
1401
1402 #[inline]
1404 pub fn to_percentage(&self) -> Percentage {
1405 Percentage(self.0.to_float() / 100.0)
1406 }
1407
1408 pub fn from_percentage(p: f32) -> Self {
1410 Self(FixedPoint::from_float((p * 100.).max(0.0).min(1000.0)))
1411 }
1412
1413 pub fn from_keyword(kw: specified::FontWidthKeyword) -> Self {
1416 use specified::FontWidthKeyword::*;
1417 match kw {
1418 UltraCondensed => Self::ULTRA_CONDENSED,
1419 ExtraCondensed => Self::EXTRA_CONDENSED,
1420 Condensed => Self::CONDENSED,
1421 SemiCondensed => Self::SEMI_CONDENSED,
1422 Normal => Self::NORMAL,
1423 SemiExpanded => Self::SEMI_EXPANDED,
1424 Expanded => Self::EXPANDED,
1425 ExtraExpanded => Self::EXTRA_EXPANDED,
1426 UltraExpanded => Self::ULTRA_EXPANDED,
1427 }
1428 }
1429
1430 pub fn as_keyword(&self) -> Option<specified::FontWidthKeyword> {
1432 use specified::FontWidthKeyword::*;
1433 if *self == Self::ULTRA_CONDENSED {
1435 return Some(UltraCondensed);
1436 }
1437 if *self == Self::EXTRA_CONDENSED {
1438 return Some(ExtraCondensed);
1439 }
1440 if *self == Self::CONDENSED {
1441 return Some(Condensed);
1442 }
1443 if *self == Self::SEMI_CONDENSED {
1444 return Some(SemiCondensed);
1445 }
1446 if *self == Self::NORMAL {
1447 return Some(Normal);
1448 }
1449 if *self == Self::SEMI_EXPANDED {
1450 return Some(SemiExpanded);
1451 }
1452 if *self == Self::EXPANDED {
1453 return Some(Expanded);
1454 }
1455 if *self == Self::EXTRA_EXPANDED {
1456 return Some(ExtraExpanded);
1457 }
1458 if *self == Self::ULTRA_EXPANDED {
1459 return Some(UltraExpanded);
1460 }
1461 None
1462 }
1463}
1464
1465impl ToCss for FontWidth {
1466 fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
1467 where
1468 W: fmt::Write,
1469 {
1470 self.to_percentage().to_css(dest)
1471 }
1472}
1473
1474impl ToTyped for FontWidth {
1475 fn to_typed(&self, dest: &mut ThinVec<TypedValue>) -> Result<(), ()> {
1476 match self.as_keyword() {
1477 Some(keyword) => keyword.to_typed(dest),
1478 None => self.to_percentage().to_typed(dest),
1479 }
1480 }
1481}
1482
1483impl ToAnimatedValue for FontWidth {
1484 type AnimatedValue = Percentage;
1485
1486 #[inline]
1487 fn to_animated_value(self, _: &crate::values::animated::Context) -> Self::AnimatedValue {
1488 self.to_percentage()
1489 }
1490
1491 #[inline]
1492 fn from_animated_value(animated: Self::AnimatedValue) -> Self {
1493 Self::from_percentage(animated.0)
1494 }
1495}
1496
1497pub type LineHeight = generics::GenericLineHeight<NonNegativeNumber, NonNegativeLength>;
1499
1500impl ToResolvedValue for LineHeight {
1501 type ResolvedValue = Self;
1502
1503 fn to_resolved_value(self, context: &ResolvedContext) -> Self::ResolvedValue {
1504 #[cfg(feature = "gecko")]
1505 {
1506 if matches!(self, Self::Normal) {
1508 return self;
1509 }
1510 let wm = context.style.writing_mode;
1511 Self::Length(
1512 context
1513 .device
1514 .calc_line_height(
1515 context.style.get_font(),
1516 wm,
1517 Some(context.element_info.element),
1518 )
1519 .to_resolved_value(context),
1520 )
1521 }
1522 #[cfg(feature = "servo")]
1523 {
1524 if let LineHeight::Number(num) = &self {
1525 let size = context
1526 .style
1527 .get_font()
1528 .slow_clone_font_size()
1529 .computed_size();
1530 LineHeight::Length(NonNegativeLength::new(size.px() * num.0))
1531 } else {
1532 self
1533 }
1534 }
1535 }
1536
1537 #[inline]
1538 fn from_resolved_value(value: Self::ResolvedValue) -> Self {
1539 value
1540 }
1541}