use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use cssparser::{BasicParseErrorKind, Parser, ParserInput};
use super::*;
use crate::units::{LayoutLength, LayoutSize, layout_pt};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) struct LayerName(pub(in crate::css) Vec<LayerSegment>);
impl LayerName {
pub(in crate::css) fn nested(&self, child: Self) -> Self {
let mut segments = self.0.clone();
segments.extend(child.0);
Self(segments)
}
pub(in crate::css) fn anonymous() -> Self {
Self(vec![LayerSegment::Anonymous(AnonymousLayerId::next())])
}
pub(in crate::css) fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(in crate::css) enum LayerSegment {
Named(String),
Anonymous(AnonymousLayerId),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(in crate::css) struct AnonymousLayerId(u64);
impl AnonymousLayerId {
fn next() -> Self {
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
Self(NEXT_ID.fetch_add(1, Ordering::Relaxed))
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) struct LayerOrder(pub(in crate::css) Vec<usize>);
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum MediaType {
#[default]
Print,
Screen,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ForcedColorPalette {
pub canvas: CssColor,
pub canvas_text: CssColor,
pub link_text: CssColor,
pub visited_text: CssColor,
pub active_text: CssColor,
pub button_face: CssColor,
pub button_text: CssColor,
pub button_border: CssColor,
pub field: CssColor,
pub field_text: CssColor,
pub highlight: CssColor,
pub highlight_text: CssColor,
pub mark: CssColor,
pub mark_text: CssColor,
pub gray_text: CssColor,
pub accent_color: CssColor,
pub accent_color_text: CssColor,
pub selected_item: CssColor,
pub selected_item_text: CssColor,
}
impl ForcedColorPalette {
pub const LIGHT: Self = Self {
canvas: CssColor::WHITE,
canvas_text: CssColor::BLACK,
link_text: CssColor::BLACK,
visited_text: CssColor::BLACK,
active_text: CssColor::BLACK,
button_face: CssColor::WHITE,
button_text: CssColor::BLACK,
button_border: CssColor::srgb_const(0.5, 0.5, 0.5, 1.0),
field: CssColor::WHITE,
field_text: CssColor::BLACK,
highlight: CssColor::WHITE,
highlight_text: CssColor::BLACK,
mark: CssColor::WHITE,
mark_text: CssColor::BLACK,
gray_text: CssColor::BLACK,
accent_color: CssColor::WHITE,
accent_color_text: CssColor::BLACK,
selected_item: CssColor::WHITE,
selected_item_text: CssColor::BLACK,
};
pub const DARK: Self = Self {
canvas: CssColor::BLACK,
canvas_text: CssColor::WHITE,
link_text: CssColor::WHITE,
visited_text: CssColor::WHITE,
active_text: CssColor::WHITE,
button_face: CssColor::BLACK,
button_text: CssColor::WHITE,
button_border: CssColor::srgb_const(0.5, 0.5, 0.5, 1.0),
field: CssColor::BLACK,
field_text: CssColor::WHITE,
highlight: CssColor::BLACK,
highlight_text: CssColor::WHITE,
mark: CssColor::BLACK,
mark_text: CssColor::WHITE,
gray_text: CssColor::WHITE,
accent_color: CssColor::BLACK,
accent_color_text: CssColor::WHITE,
selected_item: CssColor::BLACK,
selected_item_text: CssColor::WHITE,
};
}
#[derive(Debug, Clone, Copy, Default, PartialEq)]
#[allow(clippy::large_enum_variant)] pub enum ForcedColorsMode {
#[default]
Inactive,
Active(ForcedColorPalette),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SystemColor {
Canvas,
CanvasText,
LinkText,
VisitedText,
ActiveText,
ButtonFace,
ButtonText,
ButtonBorder,
Field,
FieldText,
Highlight,
HighlightText,
Mark,
MarkText,
GrayText,
AccentColor,
AccentColorText,
SelectedItem,
SelectedItemText,
}
impl ForcedColorPalette {
pub(crate) const fn color(self, system: SystemColor) -> CssColor {
match system {
SystemColor::Canvas => self.canvas,
SystemColor::CanvasText => self.canvas_text,
SystemColor::LinkText => self.link_text,
SystemColor::VisitedText => self.visited_text,
SystemColor::ActiveText => self.active_text,
SystemColor::ButtonFace => self.button_face,
SystemColor::ButtonText => self.button_text,
SystemColor::ButtonBorder => self.button_border,
SystemColor::Field => self.field,
SystemColor::FieldText => self.field_text,
SystemColor::Highlight => self.highlight,
SystemColor::HighlightText => self.highlight_text,
SystemColor::Mark => self.mark,
SystemColor::MarkText => self.mark_text,
SystemColor::GrayText => self.gray_text,
SystemColor::AccentColor => self.accent_color,
SystemColor::AccentColorText => self.accent_color_text,
SystemColor::SelectedItem => self.selected_item,
SystemColor::SelectedItemText => self.selected_item_text,
}
}
}
impl ForcedColorsMode {
pub const fn is_active(self) -> bool {
matches!(self, Self::Active(_))
}
pub const fn palette(self) -> Option<ForcedColorPalette> {
match self {
Self::Inactive => None,
Self::Active(palette) => Some(palette),
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) enum ForcedColorAdjust {
#[default]
Auto,
None,
PreserveParentColor,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CssViewportSpace {}
pub type CssViewportSize = euclid::Size2D<f32, CssViewportSpace>;
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct ViewportLengthBasis {
physical: LayoutSize,
writing_mode: WritingMode,
container_physical: Option<LayoutSize>,
}
impl ViewportLengthBasis {
pub(crate) fn for_writing_mode(physical: LayoutSize, writing_mode: WritingMode) -> Self {
Self {
physical,
writing_mode,
container_physical: None,
}
}
pub(crate) fn with_container_physical(mut self, physical: LayoutSize) -> Self {
self.container_physical = Some(physical);
self
}
pub(crate) fn vw(self, percentage: f32) -> LayoutLength {
layout_pt(percentage * self.physical.width / 100.0)
}
pub(crate) fn vh(self, percentage: f32) -> LayoutLength {
layout_pt(percentage * self.physical.height / 100.0)
}
pub(crate) fn vmin(self, percentage: f32) -> LayoutLength {
layout_pt(percentage * self.physical.width.min(self.physical.height) / 100.0)
}
pub(crate) fn vmax(self, percentage: f32) -> LayoutLength {
layout_pt(percentage * self.physical.width.max(self.physical.height) / 100.0)
}
pub(crate) fn vi(self, percentage: f32) -> LayoutLength {
match self.writing_mode {
WritingMode::HorizontalTb => self.vw(percentage),
WritingMode::VerticalRl
| WritingMode::VerticalLr
| WritingMode::SidewaysRl
| WritingMode::SidewaysLr => self.vh(percentage),
}
}
pub(crate) fn vb(self, percentage: f32) -> LayoutLength {
match self.writing_mode {
WritingMode::HorizontalTb => self.vh(percentage),
WritingMode::VerticalRl
| WritingMode::VerticalLr
| WritingMode::SidewaysRl
| WritingMode::SidewaysLr => self.vw(percentage),
}
}
pub(crate) fn container_fallback(self) -> ContainerLengthBasis {
ContainerLengthBasis::for_writing_mode(
self.container_physical.unwrap_or(self.physical),
self.writing_mode,
)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct ContainerLengthBasis {
physical: LayoutSize,
writing_mode: WritingMode,
}
impl ContainerLengthBasis {
pub(crate) fn for_writing_mode(physical: LayoutSize, writing_mode: WritingMode) -> Self {
Self {
physical,
writing_mode,
}
}
pub(crate) fn cqw(self, percentage: f32) -> LayoutLength {
layout_pt(percentage * self.physical.width / 100.0)
}
pub(crate) fn cqh(self, percentage: f32) -> LayoutLength {
layout_pt(percentage * self.physical.height / 100.0)
}
pub(crate) fn cqi(self, percentage: f32) -> LayoutLength {
match self.writing_mode {
WritingMode::HorizontalTb => self.cqw(percentage),
WritingMode::VerticalRl
| WritingMode::VerticalLr
| WritingMode::SidewaysRl
| WritingMode::SidewaysLr => self.cqh(percentage),
}
}
pub(crate) fn cqb(self, percentage: f32) -> LayoutLength {
match self.writing_mode {
WritingMode::HorizontalTb => self.cqh(percentage),
WritingMode::VerticalRl
| WritingMode::VerticalLr
| WritingMode::SidewaysRl
| WritingMode::SidewaysLr => self.cqw(percentage),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct FontRelativeLengthBasis {
font_size: LayoutLength,
ch_advance: LayoutLength,
x_height: LayoutLength,
cap_height: LayoutLength,
ic_advance: LayoutLength,
line_height: LayoutLength,
}
impl FontRelativeLengthBasis {
pub(crate) fn new(font_size: LayoutLength, ch_advance: LayoutLength) -> Self {
Self {
font_size,
ch_advance,
x_height: layout_pt(font_size.points() * 0.5),
cap_height: layout_pt(font_size.points() * 0.7),
ic_advance: font_size,
line_height: layout_pt(font_size.points() * 1.2),
}
}
pub(crate) const fn with_selected_font_metrics(
mut self,
x_height: LayoutLength,
cap_height: LayoutLength,
ic_advance: LayoutLength,
) -> Self {
self.x_height = x_height;
self.cap_height = cap_height;
self.ic_advance = ic_advance;
self
}
pub(crate) const fn with_ch_advance(mut self, ch_advance: LayoutLength) -> Self {
self.ch_advance = ch_advance;
self
}
pub(crate) const fn with_line_height(mut self, line_height: LayoutLength) -> Self {
self.line_height = line_height;
self
}
pub(crate) const fn font_size(self) -> LayoutLength {
self.font_size
}
pub(crate) const fn ch_advance(self) -> LayoutLength {
self.ch_advance
}
pub(crate) const fn line_height(self) -> LayoutLength {
self.line_height
}
pub(crate) const fn x_height(self) -> LayoutLength {
self.x_height
}
pub(crate) const fn cap_height(self) -> LayoutLength {
self.cap_height
}
pub(crate) const fn ic_advance(self) -> LayoutLength {
self.ic_advance
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct RootFontMetricLengthBasis {
pub(crate) font_size: LayoutLength,
pub(crate) ch_advance: LayoutLength,
pub(crate) x_height: LayoutLength,
pub(crate) cap_height: LayoutLength,
pub(crate) ic_advance: LayoutLength,
pub(crate) line_height: LayoutLength,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MediaEnvironment {
pub media_type: MediaType,
pub viewport: CssViewportSize,
pub resolution_dppx: f32,
pub forced_colors: ForcedColorsMode,
pub color_scheme_preference: ColorSchemePreference,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ColorSchemePreference {
#[default]
None,
Light,
Dark,
OverrideLight,
OverrideDark,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum UsedColorScheme {
Light,
Dark,
}
impl ColorSchemePreference {
pub(crate) const fn preferred(self) -> Option<UsedColorScheme> {
match self {
Self::None => None,
Self::Light | Self::OverrideLight => Some(UsedColorScheme::Light),
Self::Dark | Self::OverrideDark => Some(UsedColorScheme::Dark),
}
}
pub(crate) const fn is_override(self) -> bool {
matches!(self, Self::OverrideLight | Self::OverrideDark)
}
pub(crate) const fn media_query_scheme(self) -> UsedColorScheme {
match self {
Self::Dark | Self::OverrideDark => UsedColorScheme::Dark,
Self::None | Self::Light | Self::OverrideLight => UsedColorScheme::Light,
}
}
}
impl MediaEnvironment {
pub const fn new(media_type: MediaType, viewport: CssViewportSize) -> Self {
Self {
media_type,
viewport,
resolution_dppx: 1.0,
forced_colors: ForcedColorsMode::Inactive,
color_scheme_preference: ColorSchemePreference::None,
}
}
pub const fn with_resolution_dppx(mut self, resolution_dppx: f32) -> Self {
self.resolution_dppx = resolution_dppx;
self
}
pub const fn with_forced_colors(mut self, forced_colors: ForcedColorsMode) -> Self {
self.forced_colors = forced_colors;
self
}
pub const fn with_color_scheme_preference(
mut self,
color_scheme_preference: ColorSchemePreference,
) -> Self {
self.color_scheme_preference = color_scheme_preference;
self
}
}
impl Default for MediaEnvironment {
fn default() -> Self {
Self::new(MediaType::Print, CssViewportSize::new(793.7008, 1122.5197))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn viewport_length_basis_keeps_physical_and_logical_axes_distinct() {
let physical = LayoutSize::new(300.0, 200.0);
let horizontal = ViewportLengthBasis::for_writing_mode(physical, WritingMode::HorizontalTb);
let vertical = ViewportLengthBasis::for_writing_mode(physical, WritingMode::VerticalRl);
let sideways = ViewportLengthBasis::for_writing_mode(physical, WritingMode::SidewaysLr);
assert_eq!(horizontal.vw(100.0), layout_pt(300.0));
assert_eq!(horizontal.vh(100.0), layout_pt(200.0));
assert_eq!(horizontal.vmin(100.0), layout_pt(200.0));
assert_eq!(horizontal.vmax(100.0), layout_pt(300.0));
assert_eq!(horizontal.vi(100.0), layout_pt(300.0));
assert_eq!(horizontal.vb(100.0), layout_pt(200.0));
assert_eq!(vertical.vi(100.0), layout_pt(200.0));
assert_eq!(vertical.vb(100.0), layout_pt(300.0));
assert_eq!(sideways.vi(100.0), layout_pt(200.0));
assert_eq!(sideways.vb(100.0), layout_pt(300.0));
}
#[test]
fn color_scheme_preference_builder_preserves_preference_and_override() {
let light = ColorSchemePreference::Light;
let dark = ColorSchemePreference::Dark;
let override_light = ColorSchemePreference::OverrideLight;
let override_dark = ColorSchemePreference::OverrideDark;
assert_eq!(light.preferred(), Some(UsedColorScheme::Light));
assert_eq!(dark.preferred(), Some(UsedColorScheme::Dark));
assert_eq!(override_light.preferred(), Some(UsedColorScheme::Light));
assert_eq!(override_dark.preferred(), Some(UsedColorScheme::Dark));
assert!(!light.is_override());
assert!(!dark.is_override());
assert!(override_light.is_override());
assert!(override_dark.is_override());
let environment =
MediaEnvironment::new(MediaType::Screen, CssViewportSize::new(800.0, 600.0))
.with_color_scheme_preference(override_dark);
assert_eq!(environment.color_scheme_preference, override_dark);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub(crate) enum RgbColorSpace {
Srgb,
DisplayP3,
A98Rgb,
ProphotoRgb,
Rec2020,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum CssColorCoordinates {
Srgb(EncodedRgb<Srgb>),
DisplayP3(EncodedRgb<DisplayP3>),
A98Rgb(EncodedRgb<A98Rgb>),
ProphotoRgb(EncodedRgb<ProphotoRgb>),
Rec2020(EncodedRgb<Rec2020>),
XyzD50(D50Xyz),
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct CssRgbCoordinates {
pub(crate) red: f32,
pub(crate) green: f32,
pub(crate) blue: f32,
}
const fn rgb_components(coordinates: CssRgbCoordinates) -> [f32; 3] {
[coordinates.red, coordinates.green, coordinates.blue]
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct EncodedRgb<Space> {
coordinates: CssRgbCoordinates,
marker: std::marker::PhantomData<Space>,
}
impl<Space> EncodedRgb<Space> {
const fn new(red: f32, green: f32, blue: f32) -> Self {
Self {
coordinates: CssRgbCoordinates { red, green, blue },
marker: std::marker::PhantomData,
}
}
const fn coordinates(self) -> CssRgbCoordinates {
self.coordinates
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Srgb;
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct DisplayP3;
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct A98Rgb;
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct ProphotoRgb;
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Rec2020;
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct D50Xyz {
pub(crate) x: f32,
pub(crate) y: f32,
pub(crate) z: f32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum CssColorSpace {
Srgb,
DisplayP3,
A98Rgb,
ProphotoRgb,
Rec2020,
XyzD50,
}
impl CssColorSpace {
pub(crate) const fn cache_key(self) -> u8 {
self as u8
}
}
#[derive(Debug, Clone, Copy)]
pub struct CssColor {
coordinates: CssColorCoordinates,
alpha: CssAlpha,
pub(crate) system: Option<SystemColor>,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct CssAlpha(f32);
impl CssAlpha {
const fn new(value: f32) -> Self {
Self(value.clamp(0.0, 1.0))
}
pub(crate) const fn value(self) -> f32 {
self.0
}
}
impl PartialEq for CssColor {
fn eq(&self, other: &Self) -> bool {
self.coordinates == other.coordinates && self.alpha == other.alpha
}
}
impl CssColor {
pub const BLACK: Self = Self {
coordinates: CssColorCoordinates::Srgb(EncodedRgb::new(0.0, 0.0, 0.0)),
alpha: CssAlpha::new(1.0),
system: None,
};
pub const WHITE: Self = Self {
coordinates: CssColorCoordinates::Srgb(EncodedRgb::new(1.0, 1.0, 1.0)),
alpha: CssAlpha::new(1.0),
system: None,
};
pub const TRANSPARENT: Self = Self {
coordinates: CssColorCoordinates::Srgb(EncodedRgb::new(0.0, 0.0, 0.0)),
alpha: CssAlpha::new(0.0),
system: None,
};
const fn srgb_const(r: f32, g: f32, b: f32, a: f32) -> Self {
Self {
coordinates: CssColorCoordinates::Srgb(EncodedRgb::new(r, g, b)),
alpha: CssAlpha::new(a),
system: None,
}
}
pub fn new(r: u8, g: u8, b: u8) -> Self {
Self::rgba(r, g, b, 1.0)
}
pub fn rgba(r: u8, g: u8, b: u8, a: f32) -> Self {
Self {
coordinates: CssColorCoordinates::Srgb(EncodedRgb::new(
r as f32 / 255.0,
g as f32 / 255.0,
b as f32 / 255.0,
)),
alpha: CssAlpha::new(a),
system: None,
}
}
pub(crate) fn srgb(r: f32, g: f32, b: f32, a: f32) -> Self {
Self {
coordinates: CssColorCoordinates::Srgb(EncodedRgb::new(
r.clamp(0.0, 1.0),
g.clamp(0.0, 1.0),
b.clamp(0.0, 1.0),
)),
alpha: CssAlpha::new(a),
system: None,
}
}
pub(crate) fn rgb(space: RgbColorSpace, red: f32, green: f32, blue: f32, a: f32) -> Self {
Self {
coordinates: match space {
RgbColorSpace::Srgb => CssColorCoordinates::Srgb(EncodedRgb::new(red, green, blue)),
RgbColorSpace::DisplayP3 => {
CssColorCoordinates::DisplayP3(EncodedRgb::new(red, green, blue))
}
RgbColorSpace::A98Rgb => {
CssColorCoordinates::A98Rgb(EncodedRgb::new(red, green, blue))
}
RgbColorSpace::ProphotoRgb => {
CssColorCoordinates::ProphotoRgb(EncodedRgb::new(red, green, blue))
}
RgbColorSpace::Rec2020 => {
CssColorCoordinates::Rec2020(EncodedRgb::new(red, green, blue))
}
},
alpha: CssAlpha::new(a),
system: None,
}
}
pub(crate) fn xyz_d50(x: f32, y: f32, z: f32, a: f32) -> Self {
Self {
coordinates: CssColorCoordinates::XyzD50(D50Xyz { x, y, z }),
alpha: CssAlpha::new(a),
system: None,
}
}
pub(crate) fn in_space(
space: CssColorSpace,
first: f32,
second: f32,
third: f32,
a: f32,
) -> Self {
match space {
CssColorSpace::Srgb => Self::rgb(RgbColorSpace::Srgb, first, second, third, a),
CssColorSpace::DisplayP3 => {
Self::rgb(RgbColorSpace::DisplayP3, first, second, third, a)
}
CssColorSpace::A98Rgb => Self::rgb(RgbColorSpace::A98Rgb, first, second, third, a),
CssColorSpace::ProphotoRgb => {
Self::rgb(RgbColorSpace::ProphotoRgb, first, second, third, a)
}
CssColorSpace::Rec2020 => Self::rgb(RgbColorSpace::Rec2020, first, second, third, a),
CssColorSpace::XyzD50 => Self::xyz_d50(first, second, third, a),
}
}
pub(crate) const fn space(self) -> CssColorSpace {
match self.coordinates {
CssColorCoordinates::Srgb(_) => CssColorSpace::Srgb,
CssColorCoordinates::DisplayP3(_) => CssColorSpace::DisplayP3,
CssColorCoordinates::A98Rgb(_) => CssColorSpace::A98Rgb,
CssColorCoordinates::ProphotoRgb(_) => CssColorSpace::ProphotoRgb,
CssColorCoordinates::Rec2020(_) => CssColorSpace::Rec2020,
CssColorCoordinates::XyzD50(_) => CssColorSpace::XyzD50,
}
}
pub(crate) const fn components(self) -> [f32; 3] {
match self.coordinates {
CssColorCoordinates::Srgb(c) => rgb_components(c.coordinates()),
CssColorCoordinates::DisplayP3(c) => rgb_components(c.coordinates()),
CssColorCoordinates::A98Rgb(c) => rgb_components(c.coordinates()),
CssColorCoordinates::ProphotoRgb(c) => rgb_components(c.coordinates()),
CssColorCoordinates::Rec2020(c) => rgb_components(c.coordinates()),
CssColorCoordinates::XyzD50(c) => [c.x, c.y, c.z],
}
}
pub(crate) const fn alpha(self) -> f32 {
self.alpha.value()
}
pub(crate) const fn rgb_coordinates(self) -> Option<(RgbColorSpace, CssRgbCoordinates)> {
match self.coordinates {
CssColorCoordinates::Srgb(coordinates) => {
Some((RgbColorSpace::Srgb, coordinates.coordinates()))
}
CssColorCoordinates::DisplayP3(coordinates) => {
Some((RgbColorSpace::DisplayP3, coordinates.coordinates()))
}
CssColorCoordinates::A98Rgb(coordinates) => {
Some((RgbColorSpace::A98Rgb, coordinates.coordinates()))
}
CssColorCoordinates::ProphotoRgb(coordinates) => {
Some((RgbColorSpace::ProphotoRgb, coordinates.coordinates()))
}
CssColorCoordinates::Rec2020(coordinates) => {
Some((RgbColorSpace::Rec2020, coordinates.coordinates()))
}
CssColorCoordinates::XyzD50(_) => None,
}
}
pub(crate) const fn xyz_d50_coordinates(self) -> Option<D50Xyz> {
match self.coordinates {
CssColorCoordinates::Srgb(_)
| CssColorCoordinates::DisplayP3(_)
| CssColorCoordinates::A98Rgb(_)
| CssColorCoordinates::ProphotoRgb(_)
| CssColorCoordinates::Rec2020(_) => None,
CssColorCoordinates::XyzD50(coordinates) => Some(coordinates),
}
}
pub(crate) fn to_xyz_d50(self) -> D50Xyz {
self.xyz_d50_coordinates().unwrap_or_else(|| {
crate::css::color_to_xyz_d50(self)
.xyz_d50_coordinates()
.expect("CSS D50 conversion must produce PCS coordinates")
})
}
pub(crate) fn to_rgb_space(self, space: RgbColorSpace) -> Self {
let target = match space {
RgbColorSpace::Srgb => CssColorSpace::Srgb,
RgbColorSpace::DisplayP3 => CssColorSpace::DisplayP3,
RgbColorSpace::A98Rgb => CssColorSpace::A98Rgb,
RgbColorSpace::ProphotoRgb => CssColorSpace::ProphotoRgb,
RgbColorSpace::Rec2020 => CssColorSpace::Rec2020,
};
crate::css::color_to_predefined_rgb(self, target)
.expect("a predefined CSS RGB target must be convertible")
}
pub(crate) const fn system(system: SystemColor, color: Self) -> Self {
Self {
system: Some(system),
..color
}
}
pub(crate) const fn system_color(self) -> Option<SystemColor> {
self.system
}
pub(crate) fn with_alpha(self, alpha: f32) -> Self {
Self {
alpha: CssAlpha::new(alpha),
..self
}
}
pub(crate) fn is_visible(self) -> bool {
self.alpha.value() > 0.0
}
pub(crate) fn is_opaque(self) -> bool {
(self.alpha.value() - 1.0).abs() < 0.001
}
}
#[derive(Debug, Clone)]
pub(crate) struct Stylesheet {
pub origin: StylesheetOrigin,
pub base_url: Option<url::Url>,
pub root_url: Option<url::Url>,
pub forced_colors: ForcedColorsMode,
pub color_scheme_preference: ColorSchemePreference,
pub html_presentational_hints: bool,
pub specificity_override: Option<u32>,
pub layer_names: Vec<LayerName>,
pub namespace_prefixes: HashMap<String, String>,
pub rules: Vec<StyleRule>,
#[allow(
dead_code,
reason = "container-query matching is retained for layout-time implementation"
)]
pub container_rules: Vec<ContainerRule>,
pub keyframes: Vec<KeyframesRule>,
pub marker_rules: Vec<StyleRule>,
pub before_marker_rules: Vec<StyleRule>,
pub after_marker_rules: Vec<StyleRule>,
pub before_rules: Vec<StyleRule>,
pub after_rules: Vec<StyleRule>,
pub scroll_marker_rules: Vec<StyleRule>,
pub scroll_marker_group_rules: Vec<StyleRule>,
pub footnote_call_rules: Vec<StyleRule>,
pub footnote_marker_rules: Vec<StyleRule>,
pub first_line_rules: Vec<StyleRule>,
pub first_letter_rules: Vec<StyleRule>,
pub page_rules: Vec<PageRule>,
#[cfg_attr(not(test), allow(dead_code))]
pub page_declarations: Declarations,
pub first_page_declarations: Declarations,
pub font_faces: Vec<CssFontFace>,
pub font_feature_values: FontFeatureValues,
pub font_palette_values: FontPaletteValues,
pub counter_styles: Vec<CounterStyleRule>,
pub property_registrations: Vec<PropertyRegistrationRule>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct HtmlContainerFrameBodyMargins {
pub(crate) horizontal: Option<i32>,
pub(crate) vertical: Option<i32>,
}
impl HtmlContainerFrameBodyMargins {
pub(crate) fn from_iframe_attributes(attrs: &HashMap<String, String>) -> Self {
Self {
horizontal: attrs
.get("marginwidth")
.and_then(|value| parse_html_non_negative_integer(value)),
vertical: attrs
.get("marginheight")
.and_then(|value| parse_html_non_negative_integer(value)),
}
}
}
pub(crate) fn parse_html_non_negative_integer(value: &str) -> Option<i32> {
let value = value.trim_start_matches(is_html_space);
let (sign, rest) = match value.as_bytes().first().copied() {
Some(b'+') => (1, &value[1..]),
Some(b'-') => (-1, &value[1..]),
_ => (1, value),
};
let digit_len = rest.bytes().take_while(u8::is_ascii_digit).count();
if digit_len == 0 {
return None;
}
let integer = rest[..digit_len].parse::<i32>().ok()? * sign;
(integer >= 0).then_some(integer)
}
fn is_html_space(character: char) -> bool {
matches!(character, ' ' | '\t' | '\n' | '\u{0c}' | '\r')
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Stylesheets<'a> {
user_agent: Option<&'static Stylesheet>,
html_important: Option<&'static Stylesheet>,
document: &'a [Stylesheet],
html_container_frame_body_margins: Option<HtmlContainerFrameBodyMargins>,
image_set_resolution_dppx: f32,
#[cfg(test)]
borrowed: &'a [&'a Stylesheet],
}
pub(crate) static EMPTY_STYLESHEETS: Stylesheets<'static> = Stylesheets::document_only(&[]);
pub(crate) trait StylesheetCollection {
fn stylesheet_view(&self) -> Stylesheets<'_>;
}
impl StylesheetCollection for Stylesheets<'_> {
fn stylesheet_view(&self) -> Stylesheets<'_> {
*self
}
}
impl StylesheetCollection for [Stylesheet] {
fn stylesheet_view(&self) -> Stylesheets<'_> {
Stylesheets::document_only(self)
}
}
impl StylesheetCollection for Vec<Stylesheet> {
fn stylesheet_view(&self) -> Stylesheets<'_> {
Stylesheets::document_only(self)
}
}
impl<const LENGTH: usize> StylesheetCollection for [Stylesheet; LENGTH] {
fn stylesheet_view(&self) -> Stylesheets<'_> {
Stylesheets::document_only(self)
}
}
impl<'a> Stylesheets<'a> {
pub(crate) const fn document_only(document: &'a [Stylesheet]) -> Self {
Self {
user_agent: None,
html_important: None,
document,
html_container_frame_body_margins: None,
image_set_resolution_dppx: 1.0,
#[cfg(test)]
borrowed: &[],
}
}
pub(crate) const fn for_document(
user_agent: &'static Stylesheet,
html_important: Option<&'static Stylesheet>,
document: &'a [Stylesheet],
) -> Self {
Self {
user_agent: Some(user_agent),
html_important,
document,
html_container_frame_body_margins: None,
image_set_resolution_dppx: 1.0,
#[cfg(test)]
borrowed: &[],
}
}
#[cfg(test)]
pub(crate) const fn borrowed(stylesheets: &'a [&'a Stylesheet]) -> Self {
Self {
user_agent: None,
html_important: None,
document: &[],
html_container_frame_body_margins: None,
image_set_resolution_dppx: 1.0,
borrowed: stylesheets,
}
}
pub(crate) const fn with_html_container_frame_body_margins(
mut self,
margins: Option<HtmlContainerFrameBodyMargins>,
) -> Self {
self.html_container_frame_body_margins = margins;
self
}
pub(crate) const fn with_image_set_resolution_dppx(mut self, resolution_dppx: f32) -> Self {
self.image_set_resolution_dppx = resolution_dppx;
self
}
pub(crate) const fn image_set_resolution_dppx(self) -> f32 {
self.image_set_resolution_dppx
}
pub(crate) const fn html_container_frame_body_margins(
self,
) -> Option<HtmlContainerFrameBodyMargins> {
self.html_container_frame_body_margins
}
pub(crate) fn iter(&self) -> impl DoubleEndedIterator<Item = &Stylesheet> + Clone {
let stylesheets = self
.user_agent
.iter()
.copied()
.chain(self.html_important.iter().copied())
.chain(self.document.iter());
#[cfg(test)]
{
stylesheets.chain(self.borrowed.iter().copied())
}
#[cfg(not(test))]
{
stylesheets
}
}
pub(crate) const fn len(&self) -> usize {
let len = self.user_agent.is_some() as usize
+ self.html_important.is_some() as usize
+ self.document.len();
#[cfg(not(test))]
{
len
}
#[cfg(test)]
{
len + self.borrowed.len()
}
}
pub(crate) fn get(&self, index: usize) -> Option<&Stylesheet> {
self.iter().nth(index)
}
pub(crate) fn color_scheme_preference(self) -> ColorSchemePreference {
self.iter()
.rev()
.find_map(|stylesheet| {
(stylesheet.color_scheme_preference != ColorSchemePreference::None)
.then_some(stylesheet.color_scheme_preference)
})
.unwrap_or(ColorSchemePreference::None)
}
pub(crate) fn registered_custom_properties(self) -> RegisteredCustomProperties {
RegisteredCustomProperties::from_rules(self.iter())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) enum StylesheetOrigin {
UserAgent,
User,
Author,
}
#[derive(Debug, Clone)]
pub(crate) struct PageRule {
pub origin: StylesheetOrigin,
pub selectors: Vec<PageSelector>,
pub declarations: Declarations,
pub margin_boxes: HashMap<String, Declarations>,
pub footnote_area: Option<Declarations>,
pub order: usize,
pub layer_order: Option<LayerOrder>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PageSelector {
pub page_type: Option<String>,
pub pseudos: Vec<PagePseudo>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PagePseudo {
First,
Left,
Right,
Blank,
Nth { a: i32, b: i32 },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct PageSpecificity {
pub page_type_names: u16,
pub first_or_blank: u16,
pub left_or_right: u16,
}
impl PageSelector {
pub fn matches(
&self,
page_number: usize,
page_name: Option<&str>,
is_blank: bool,
page_progression_direction: Direction,
) -> bool {
if let Some(page_type) = &self.page_type
&& page_name != Some(page_type.as_str())
{
return false;
}
self.pseudos.iter().all(|pseudo| match pseudo {
PagePseudo::First => page_number == 1,
PagePseudo::Left => page_is_left(page_number, page_progression_direction),
PagePseudo::Right => !page_is_left(page_number, page_progression_direction),
PagePseudo::Blank => is_blank,
PagePseudo::Nth { a, b } => nth_page_matches(*a, *b, page_number),
})
}
pub fn specificity(&self) -> PageSpecificity {
let mut specificity = PageSpecificity {
page_type_names: u16::from(self.page_type.is_some()),
first_or_blank: 0,
left_or_right: 0,
};
for pseudo in &self.pseudos {
match pseudo {
PagePseudo::First | PagePseudo::Blank | PagePseudo::Nth { .. } => {
specificity.first_or_blank = specificity.first_or_blank.saturating_add(1);
}
PagePseudo::Left | PagePseudo::Right => {
specificity.left_or_right = specificity.left_or_right.saturating_add(1);
}
}
}
specificity
}
}
fn nth_page_matches(a: i32, b: i32, page_number: usize) -> bool {
let page_number = i32::try_from(page_number).unwrap_or(i32::MAX);
if a == 0 {
return page_number == b;
}
let delta = page_number - b;
if a > 0 {
delta >= 0 && delta % a == 0
} else {
delta <= 0 && delta % a == 0
}
}
impl PageRule {
pub fn matching_specificity(
&self,
page_number: usize,
page_name: Option<&str>,
is_blank: bool,
page_progression_direction: Direction,
) -> Option<PageSpecificity> {
if self.selectors.is_empty() {
return Some(PageSpecificity {
page_type_names: 0,
first_or_blank: 0,
left_or_right: 0,
});
}
self.selectors
.iter()
.filter(|selector| {
selector.matches(page_number, page_name, is_blank, page_progression_direction)
})
.map(PageSelector::specificity)
.max()
}
}
fn page_is_left(page_number: usize, page_progression_direction: Direction) -> bool {
match page_progression_direction {
Direction::Ltr => page_number.is_multiple_of(2),
Direction::Rtl => !page_number.is_multiple_of(2),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct CounterStyleRule {
pub name: String,
pub system: CounterStyleSystem,
pub symbols: Vec<String>,
pub additive_symbols: Vec<(i32, String)>,
pub prefix: Option<String>,
pub suffix: Option<String>,
pub negative: Option<(String, String)>,
pub pad: Option<(usize, String)>,
pub range: Option<CounterStyleRange>,
pub fallback: Option<String>,
pub speak_as: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum CounterStyleRange {
Auto,
Intervals(Vec<CounterStyleRangeInterval>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct CounterStyleRangeInterval {
pub start: i64,
pub end: i64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum CounterStyleSystem {
Cyclic,
Numeric,
Alphabetic,
Symbolic,
Fixed(i32),
Additive,
Extends(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct CssFontFace {
pub family: String,
pub sources: Vec<FontFaceSource>,
pub unicode_range: Option<Vec<UnicodeRange>>,
pub size_adjust: Option<u32>,
pub ascent_override: Option<u32>,
pub descent_override: Option<u32>,
pub line_gap_override: Option<u32>,
pub weight: FontWeight,
pub weight_is_variable: bool,
pub style: FontStyle,
pub width: FontWidth,
pub width_is_variable: bool,
pub font_variation_settings: FontVariationSettings,
pub font_feature_settings: FontFeatureSettings,
pub font_variant_ligatures: FontVariantLigatures,
pub font_variant_position: FontVariantPosition,
pub font_variant_caps: FontVariantCaps,
pub font_variant_numeric: FontVariantNumeric,
pub font_variant_alternates: FontVariantAlternates,
pub font_variant_east_asian: FontVariantEastAsian,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct UnicodeRange {
pub(crate) start: u32,
pub(crate) end: u32,
}
impl UnicodeRange {
pub(crate) const ALL: Self = Self {
start: 0,
end: 0x10ffff,
};
pub(crate) fn contains(self, character: char) -> bool {
let scalar = character as u32;
self.start <= scalar && scalar <= self.end
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum FontFaceSource {
Url {
value: String,
base_url: Option<url::Url>,
root_url: Option<url::Url>,
},
}
#[derive(Debug, Clone)]
pub(crate) struct StyleRule {
pub selector_text: String,
pub selector: SelectorList<SpindriftSelectorImpl>,
pub stylesheet_scope_anchor: StylesheetScopeAnchor,
pub declarations: Declarations,
#[allow(dead_code)]
pub specificity: u32,
pub routed_pseudo_specificity: u32,
pub order: usize,
pub layer_name: Option<LayerName>,
pub scopes: Vec<ScopeRule>,
}
#[allow(
dead_code,
reason = "container-query matching is retained for layout-time implementation"
)]
#[derive(Debug, Clone)]
pub(crate) struct ContainerRule {
pub prelude: String,
pub rules: Vec<StyleRule>,
pub nested: Vec<ContainerRule>,
}
#[allow(
dead_code,
reason = "container-query matching is retained for layout-time implementation"
)]
impl ContainerRule {
pub(crate) fn name_and_condition(&self) -> (Option<&str>, &str) {
let prelude = self.prelude.trim();
let Some(condition_start) = prelude.find('(') else {
return (None, prelude);
};
let name = prelude[..condition_start].trim();
(
(!name.is_empty()).then_some(name),
prelude[condition_start..].trim(),
)
}
pub(crate) fn rules(&self) -> &[StyleRule] {
&self.rules
}
pub(crate) fn nested(&self) -> &[ContainerRule] {
&self.nested
}
}
impl Stylesheet {
#[allow(
dead_code,
reason = "container-query matching is retained for layout-time implementation"
)]
pub(crate) fn container_rules(&self) -> &[ContainerRule] {
&self.container_rules
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct KeyframesName(String);
impl KeyframesName {
pub(in crate::css) fn parse<'i, 't>(
input: &mut Parser<'i, 't>,
) -> Result<Self, cssparser::ParseError<'i, BasicParseErrorKind<'i>>> {
if let Ok(ident) = input.try_parse(|input| input.expect_ident_cloned()) {
if Self::unquoted_identifier_is_reserved(&ident) {
return Err(input.new_custom_error(BasicParseErrorKind::QualifiedRuleInvalid));
}
input.expect_exhausted()?;
return Ok(Self(ident.to_string()));
}
let string = input.expect_string_cloned()?;
input.expect_exhausted()?;
Ok(Self(string.to_string()))
}
pub(in crate::css) fn parse_css(value: &str) -> Option<Self> {
let mut input = ParserInput::new(value);
let mut parser = Parser::new(&mut input);
Self::parse(&mut parser).ok()
}
pub(in crate::css) fn to_css_string(&self) -> String {
let mut output = String::with_capacity(self.0.len() + 2);
output.push('"');
for character in self.0.chars() {
match character {
'"' | '\\' => {
output.push('\\');
output.push(character);
}
'\n' => output.push_str("\\a "),
'\r' => output.push_str("\\d "),
'\u{000C}' => output.push_str("\\c "),
character => output.push(character),
}
}
output.push('"');
output
}
#[cfg(test)]
pub(crate) fn as_str(&self) -> &str {
&self.0
}
fn unquoted_identifier_is_reserved(value: &str) -> bool {
matches!(
value.to_ascii_lowercase().as_str(),
"initial" | "inherit" | "unset" | "revert" | "revert-layer" | "default" | "none"
)
}
}
#[derive(Debug, Clone)]
pub(crate) struct KeyframesRule {
pub(crate) name: KeyframesName,
pub(crate) steps: Vec<KeyframeStep>,
}
#[derive(Debug, Clone)]
pub(crate) struct KeyframeStep {
pub(crate) offset: f32,
pub(crate) declarations: Declarations,
}
#[derive(Debug, Clone)]
pub(crate) struct ScopeRule {
pub root: ScopeRoot,
pub limit: Option<SelectorList<SpindriftSelectorImpl>>,
}
#[derive(Debug, Clone)]
pub(crate) enum ScopeRoot {
Explicit(SelectorList<SpindriftSelectorImpl>),
Owner(StylesheetScopeAnchor),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum StylesheetScopeAnchor {
DocumentRoot,
Element(crate::dom::ElementId),
}
#[derive(Debug, Clone, Default)]
pub(crate) struct Declarations {
items: Vec<(String, String)>,
base_url: Option<url::Url>,
root_url: Option<url::Url>,
}
impl Declarations {
pub fn new() -> Self {
Self {
items: Vec::new(),
base_url: None,
root_url: None,
}
}
pub fn with_urls(mut self, base_url: Option<&url::Url>, root_url: Option<&url::Url>) -> Self {
self.base_url = base_url.cloned();
self.root_url = root_url.cloned();
self
}
pub fn base_url(&self) -> Option<&url::Url> {
self.base_url.as_ref()
}
pub fn root_url(&self) -> Option<&url::Url> {
self.root_url.as_ref()
}
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
pub fn get(&self, name: &str) -> Option<&String> {
self.items
.iter()
.rev()
.find_map(|(key, value)| (key == name).then_some(value))
}
pub(crate) fn iter(&self) -> std::slice::Iter<'_, (String, String)> {
self.items.iter()
}
pub fn extend(&mut self, declarations: Declarations) {
self.items.extend(declarations.items);
}
}
impl FromIterator<(String, String)> for Declarations {
fn from_iter<T: IntoIterator<Item = (String, String)>>(iter: T) -> Self {
Self {
items: iter.into_iter().collect(),
base_url: None,
root_url: None,
}
}
}
impl<'a> IntoIterator for &'a Declarations {
type Item = &'a (String, String);
type IntoIter = std::slice::Iter<'a, (String, String)>;
fn into_iter(self) -> Self::IntoIter {
self.items.iter()
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Edges {
pub top: f32,
pub right: f32,
pub bottom: f32,
pub left: f32,
}
impl Edges {
pub const ZERO: Self = Self {
top: 0.0,
right: 0.0,
bottom: 0.0,
left: 0.0,
};
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct OptionalEdges<T> {
pub top: Option<T>,
pub right: Option<T>,
pub bottom: Option<T>,
pub left: Option<T>,
}
impl<T> OptionalEdges<T> {
pub const NONE: Self = Self {
top: None,
right: None,
bottom: None,
left: None,
};
}