Truly independent web browser
/*
* Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
//! Native absolutization of style values.
//!
//! Mirrors the C++ `StyleValue::absolutized(ComputationContext const&)` dispatch: structural
//! values recurse into their children and rebuild only when a child changed, dimensions convert
//! to their canonical units, and lengths resolve through the shared length-resolution context.
//! Preserving identity for unchanged values is a real contract: the store batch reuses wrappers
//! and shared allocations based on pointer equality.
// Style value data allocations are thread-confined, like style_value.rs.
use crate::css::style_value::{
BackgroundSizePayload, BorderImageSlicePayload, BorderRadiusPayload, BorderRadiusRectPayload, ColorFunctionPayload,
ColorMixPayload, ConicGradientPayload, ContentPayload, CounterDefinitionsPayload, CounterStyleSystemPayload,
CursorPayload, EasingPayload, FunctionPayload, GridTrackPlacementPayload, GridTrackSizeListPayload, ImagePayload,
ImageSetPayload, LightDarkPayload, LinearGradientPayload, OpenTypeTaggedPayload, PositionPayload,
RadialGradientPayload, RadialSizePayload, RandomValueSharingPayload, RatioPayload, RayPayload, RectPayload,
ScrollbarColorPayload, ShadowPayload, StyleValueBox, TransformationPayload, UrlPayload,
};
use crate::css::style_value_arc::StyleValueArc;
use std::cell::Cell;
#[cfg(test)]
mod grid_tests {
use super::*;
use crate::css::css_tokenizer::{TokenizerInput, tokenize_for_parser};
use crate::css::parser::component_value::consume_a_list_of_component_values;
use crate::css::parser::value_parser::{ParseContext, ParseOutcome, parse_css_value};
use crate::css::property_metadata::property_id;
/// Absolutizes against a zeroed length context, handing back the value itself when it is
/// unchanged.
fn absolutize_for_test(value: &StyleValueData) -> StyleValueArc {
// All fields are scalars or nullable pointers.
let length = FfiLengthResolutionContext::default();
let context = AbsolutizationContext {
length: &length,
scheme: None,
resolved_viewport_relative_length: Cell::new(false),
tree_counting: None,
random_base_values: &[],
document_base_url: &[],
style_sheet_resource_context: None,
current_color: None,
};
match absolutize(value, &context).unwrap() {
Absolutized::Unchanged => unsafe {
StyleValueArc::increment_strong_count(value);
StyleValueArc::from_raw(value)
},
Absolutized::Changed(value) => value.into_arc(),
}
}
fn parse(property: u16, source: &str) -> StyleValueArc {
let units: Vec<_> = source.encode_utf16().collect();
let values = consume_a_list_of_component_values(tokenize_for_parser(TokenizerInput::Utf16(&units))).unwrap();
// All fields are scalars or nullable pointers.
let context = ParseContext::default();
let ParseOutcome::Parsed(value) = parse_css_value(&context, property, &values) else {
panic!("invalid test value");
};
value
}
#[test]
fn composite_resolution_preserves_shared_shapes_and_easing() {
for (property, source) in [
(property_id::CLIP_PATH, "inset(1px round 2px)"),
(property_id::CLIP_PATH, "circle(2px at 25% 75%)"),
(property_id::CLIP_PATH, "ellipse(2px 3px)"),
(property_id::CLIP_PATH, "polygon(1px 2px, 3px 4px, 5px 6px)"),
(property_id::D, "path(\"M0 0 L30 40\")"),
(property_id::ANIMATION_TIMING_FUNCTION, "linear(0 0%, 1 50%)"),
(property_id::ANIMATION_TIMING_FUNCTION, "cubic-bezier(0, 0, 1, 1)"),
(property_id::ANIMATION_TIMING_FUNCTION, "steps(4, jump-start)"),
] {
let parsed = parse(property, source);
let value = match &*parsed {
StyleValueData::ValueList { values, .. } => values.as_slice()[0].data(),
value => value,
};
let same = absolutize_for_test(value);
assert!(std::ptr::eq(value, &*same));
let mut children = Vec::new();
let mut retain_child = |child: &RetainedStyleValueData, _: &mut bool| {
if child.optional_data().is_some() {
children.push((
child.clone(),
crate::css::serialize::serialize_style_value_to_utf16(child.data()),
));
}
Some(child.clone())
};
match value {
StyleValueData::BasicShape { .. } => {
absolutize_basic_shape(value, &mut retain_child).unwrap();
}
StyleValueData::Easing { .. } => {
absolutize_easing(value, &mut retain_child).unwrap();
}
_ => unreachable!(),
}
drop(same);
drop(parsed);
for (child, expected) in children {
assert_eq!(
crate::css::serialize::serialize_style_value_to_utf16(child.data()),
expected
);
}
}
}
#[test]
fn composite_resolution_resolves_contrast_color() {
let parsed = parse(property_id::COLOR, "contrast-color(red)");
let resolved = absolutize_for_test(&parsed);
assert!(matches!(&*resolved, StyleValueData::ColorFunction { .. }));
assert_eq!(
to_color(&resolved, &EMPTY_INPUT),
Some(crate::css::color_resolution::Rgba::BLACK)
);
}
#[test]
fn composite_resolution_canonicalizes_linear_easing_control_points() {
let parsed = parse(property_id::ANIMATION_TIMING_FUNCTION, "linear(0, 0.25, 0.5 60%, 1)");
let StyleValueData::ValueList { values, .. } = &*parsed else {
unreachable!();
};
let resolved = absolutize_for_test(values.as_slice()[0].data());
let StyleValueData::Easing(easing_payload) = &*resolved else {
unreachable!();
};
let EasingPayload { linear_stops, .. } = &**easing_payload;
let inputs = linear_stops
.as_slice()
.iter()
.map(|stop| {
let StyleValueData::Percentage { value } = stop.input().data() else {
unreachable!();
};
*value
})
.collect::<Vec<_>>();
assert_eq!(inputs, [0.0, 30.0, 60.0, 100.0]);
}
#[test]
fn grid_leaf_resolution_preserves_identity_and_retained_children() {
for (property, source) in [
(property_id::GRID_ROW_START, "3"),
(
property_id::GRID_TEMPLATE_COLUMNS,
"[雪] repeat(2, minmax(10px, 1fr)) [雨]",
),
] {
let value = parse(property, source);
let original = crate::css::serialize::serialize_style_value_to_utf16(&value);
let same = absolutize_for_test(&value);
assert!(StyleValueArc::ptr_eq(&value, &same));
let mut retained = Vec::new();
let mapped = map_grid_values(&value, &mut |child| {
if child.optional_data().is_some() {
retained.push(child.clone());
}
Some(child.clone())
})
.unwrap();
drop(value);
drop(same);
assert!(!retained.is_empty());
assert_eq!(crate::css::serialize::serialize_style_value_to_utf16(&mapped), original);
drop(mapped);
for child in retained {
crate::css::serialize::serialize_style_value_to_utf16(child.data());
}
}
}
#[test]
fn grid_leaf_resolution_rebuilds_nested_tracks_without_changing_the_source() {
let value = parse(
property_id::GRID_TEMPLATE_COLUMNS,
"[雪] repeat(2, minmax(10px, 1fr)) [雨]",
);
let resolved = StyleValueArc::new(
map_grid_values(&value, &mut |child| {
Some(match child.optional_data() {
Some(StyleValueData::Length { value, unit }) => retain_new(StyleValueData::Length {
value: value * 2.0,
unit: *unit,
}),
_ => child.clone(),
})
})
.unwrap(),
);
assert!(!StyleValueArc::ptr_eq(&value, &resolved));
for (value, expected) in [
(&value, "[雪] repeat(2, minmax(10px, 1fr)) [雨]"),
(&resolved, "[雪] repeat(2, minmax(20px, 1fr)) [雨]"),
] {
assert_eq!(
crate::css::serialize::serialize_style_value_to_utf16(value),
expected.encode_utf16().collect::<Vec<_>>()
);
}
}
}
use crate::css::color_resolution::{
ColorResolutionInput, EMPTY_INPUT, PREFERRED_COLOR_SCHEME_DARK, RECTANGULAR_COLOR_SPACE_OKLAB,
calculate_a_color_mix, descriptor_for_color_type, percentage_from_style_value, resolve_alpha, resolve_hue,
resolve_relative_form, resolve_with_reference_value, to_color,
};
use crate::css::css_enums::keyword;
use crate::css::serialize::color_function_has_missing_component;
use crate::css::style_compute::{FfiLengthResolutionContext, absolutize_length, keyword_is_color};
use crate::css::style_value::{
BasicShapeData, ColorBase, CssString, OwnedBasicShapeData, RetainedGridTrackEntryList, RetainedStyleValueData,
RetainedStyleValueDataList, StyleValueData, is_none_keyword, value_depends_on_current_color,
};
use crate::css::value_codes::*;
pub(crate) struct AbsolutizationContext<'a> {
pub(crate) length: &'a FfiLengthResolutionContext,
/// The used color scheme, present exactly when the C++ computation context carries one:
/// only the generic context kind sets it. PreferredColorScheme codes; Dark is 1.
pub(crate) scheme: Option<u8>,
/// Set when a viewport-relative length resolved, mirroring the C++ tracking flag.
pub(crate) resolved_viewport_relative_length: Cell<bool>,
/// Immutable sibling facts supplied only when a winning cascaded value uses a
/// tree-counting function.
pub(crate) tree_counting: Option<(u64, u64)>,
/// Random base values captured before entering the longhand drive.
pub(crate) random_base_values: &'a [crate::css::style_compute::FfiRandomBaseValue],
/// The document base URL captured before entering the longhand drive.
pub(crate) document_base_url: &'a [u8],
/// The stylesheet resource context for the selected cascade source, if any.
pub(crate) style_sheet_resource_context: Option<StyleSheetResourceContext<'a>>,
/// The computed value `currentcolor` names while the value computes, which only the `color` property knows: its
/// inherited value. Elsewhere `currentcolor` names the element's own color, which the computed value keeps
/// unresolved until it is used.
pub(crate) current_color: Option<&'a StyleValueData>,
}
#[derive(Clone, Copy)]
pub(crate) struct StyleSheetResourceContext<'a> {
pub(crate) base_url: &'a [u8],
pub(crate) origin_clean: bool,
}
/// The outcome for one value: unchanged (preserve identity) or a new allocation.
pub(crate) enum Absolutized {
Unchanged,
Changed(RetainedStyleValueData),
}
fn retain_new(value: StyleValueData) -> RetainedStyleValueData {
RetainedStyleValueData::from_arc(StyleValueArc::new(value))
}
/// Absolutizes one retained child slot. Returns the child for the rebuilt parent, whether any
/// change happened, or None when the child's absolutization declined. Null children stay null.
fn absolutize_child(
child: &RetainedStyleValueData,
context: &AbsolutizationContext,
any_changed: &mut bool,
) -> Option<RetainedStyleValueData> {
let Some(data) = child.optional_data() else {
return Some(child.clone_retained());
};
match absolutize(data, context)? {
Absolutized::Unchanged => Some(child.clone_retained()),
Absolutized::Changed(new_child) => {
*any_changed = true;
Some(new_child)
}
}
}
fn absolutize_list(
values: &RetainedStyleValueDataList,
context: &AbsolutizationContext,
any_changed: &mut bool,
) -> Option<Vec<RetainedStyleValueData>> {
values
.as_slice()
.iter()
.map(|child| absolutize_child(child, context, any_changed))
.collect()
}
/// The absolutized children of a list, or none where every child is unchanged, allocating only once
/// one changes.
fn absolutize_list_if_changed(
values: &RetainedStyleValueDataList,
context: &AbsolutizationContext,
) -> Option<Option<Vec<RetainedStyleValueData>>> {
let values = values.as_slice();
let mut changed: Option<Vec<RetainedStyleValueData>> = None;
for (index, child) in values.iter().enumerate() {
let absolutized = match child.optional_data() {
Some(data) => absolutize(data, context)?,
None => Absolutized::Unchanged,
};
match (absolutized, &mut changed) {
(Absolutized::Unchanged, None) => {}
(Absolutized::Unchanged, Some(changed)) => changed.push(child.clone_retained()),
(Absolutized::Changed(new_child), Some(changed)) => changed.push(new_child),
(Absolutized::Changed(new_child), None) => {
let mut list = Vec::with_capacity(values.len());
list.extend(values[..index].iter().map(RetainedStyleValueData::clone_retained));
list.push(new_child);
changed = Some(list);
}
}
}
Some(changed)
}
fn zero_px_length() -> StyleValueData {
StyleValueData::Length {
value: 0.0,
unit: crate::css::style_compute::px_length_unit(),
}
}
fn currentcolor_keyword() -> StyleValueData {
StyleValueData::Keyword {
keyword: keyword::CURRENTCOLOR,
}
}
// ColorStyleValue.h: ColorSyntax::Legacy = 0, Modern = 1.
fn retained_null() -> RetainedStyleValueData {
RetainedStyleValueData::none()
}
fn absolutize_image(value: &StyleValueData, context: &AbsolutizationContext) -> Option<Absolutized> {
let StyleValueData::Image(image_payload) = value else {
return None;
};
let ImagePayload {
url,
url_type,
url_modifiers,
resource_context,
} = &**image_payload;
// https://drafts.csswg.org/css-values-4/#local-urls
// When serializing a url() with the local url flag set, it must serialize as just the fragment.
if url.is_empty() || url.is_fragment() {
return Some(Absolutized::Unchanged);
}
let base_url = context
.style_sheet_resource_context
.map(|resource_context| resource_context.base_url)
.filter(|base_url| !base_url.is_empty())
.or_else(|| {
resource_context
.has_base_url
.then(|| resource_context.base_url.ascii_bytes())
})
.unwrap_or(context.document_base_url);
if base_url.is_empty() {
return Some(Absolutized::Unchanged);
}
let url_string = url.url_input();
let should_absolutize_url_for_computed_value =
context.style_sheet_resource_context.is_some() || resource_context.should_absolutize_url_for_computed_value;
let absolutized_url = if should_absolutize_url_for_computed_value {
if liburl_rust::basic_parse(url_string, liburl_rust::BasicParseOptions::new()).is_some() {
url.clone()
} else {
let base_url = std::str::from_utf8(base_url).ok()?;
let base_url = liburl_rust::basic_parse(base_url, liburl_rust::BasicParseOptions::new())?;
let resolved_url =
liburl_rust::basic_parse(url_string, liburl_rust::BasicParseOptions::new().base_url(&base_url));
let Some(resolved_url) = resolved_url else {
return Some(Absolutized::Unchanged);
};
crate::css::style_value::RetainedString::from_ascii(resolved_url.into())
}
} else {
url.clone()
};
let base_url = std::str::from_utf8(base_url).ok()?;
let base_url = crate::css::style_value::RetainedString::from_ascii(base_url.to_owned());
let (has_parent_style_sheet_origin_clean, parent_style_sheet_origin_clean) = context
.style_sheet_resource_context
.map(|context| (true, context.origin_clean))
.unwrap_or((
resource_context.has_parent_style_sheet_origin_clean,
resource_context.parent_style_sheet_origin_clean,
));
Some(Absolutized::Changed(retain_new(StyleValueData::Image(
StyleValueBox::new(ImagePayload {
url: absolutized_url,
url_type: *url_type,
url_modifiers: url_modifiers.clone(),
resource_context: crate::css::style_value::ImageResourceContext {
base_url,
has_base_url: true,
has_parent_style_sheet_origin_clean,
parent_style_sheet_origin_clean,
should_absolutize_url_for_computed_value,
},
}),
))))
}
/// The color-resolution input the C++ absolutizers build from a computation context: the
/// context's color scheme and calculation inputs, the currentcolor it knows of, and no channels.
fn color_resolution_input<'a>(context: &'a AbsolutizationContext) -> ColorResolutionInput<'a> {
let mut input = ColorResolutionInput {
scheme: context.scheme,
current_color: None,
current_color_value: None,
length: Some(context.length),
channels: None,
};
if let Some(current_color) = context.current_color {
input.current_color = to_color(current_color, &input);
input.current_color_value = Some(current_color);
}
input
}
/// The rgb() function form ColorFunctionStyleValue::create builds for an already-resolved
/// color: number channels, a number alpha, no name and no origin.
fn rgb_color_function(r: f64, g: f64, b: f64, alpha: f64, color_syntax: u8) -> StyleValueData {
StyleValueData::ColorFunction(StyleValueBox::new(ColorFunctionPayload {
color_base: ColorBase {
has_color_type: true,
color_type: crate::css::color_conversion::RGB,
color_syntax,
},
channel_0: RetainedStyleValueData::from_owned(StyleValueData::Number { value: r }),
channel_1: RetainedStyleValueData::from_owned(StyleValueData::Number { value: g }),
channel_2: RetainedStyleValueData::from_owned(StyleValueData::Number { value: b }),
alpha: RetainedStyleValueData::from_owned(StyleValueData::Number { value: alpha }),
has_name: false,
name: CssString::none(),
origin_color: retained_null(),
}))
}
/// The canonical computed form of a fully-resolved legacy sRGB color.
fn canonical_legacy_rgb(value: &StyleValueData) -> Option<StyleValueData> {
let rgba = crate::css::color_resolution::to_color(value, &EMPTY_INPUT)?;
Some(rgb_color_function(
f64::from(rgba.r),
f64::from(rgba.g),
f64::from(rgba.b),
f64::from(rgba.a) / 255.0,
COLOR_SYNTAX_LEGACY,
))
}
/// Whether `value` is the canonical computed form of a fully-resolved opaque legacy sRGB color, which
/// computes to itself.
pub(crate) fn color_function_is_canonical_legacy_rgb(value: &StyleValueData) -> bool {
let StyleValueData::ColorFunction(color_function) = value else {
return false;
};
let channel_is_a_byte = |channel: &RetainedStyleValueData| {
matches!(channel.optional_data(), Some(StyleValueData::Number { value })
if (0.0..=255.0).contains(value) && value.fract() == 0.0)
};
color_function.color_base.has_color_type
&& color_function.color_base.color_type == crate::css::color_conversion::RGB
&& color_function.color_base.color_syntax == COLOR_SYNTAX_LEGACY
&& !color_function.has_name
&& color_function.origin_color.optional_data().is_none()
&& channel_is_a_byte(&color_function.channel_0)
&& channel_is_a_byte(&color_function.channel_1)
&& channel_is_a_byte(&color_function.channel_2)
&& matches!(color_function.alpha.optional_data(), Some(StyleValueData::Number { value }) if *value == 1.0)
}
/// Port of hsl_to_absolutized_rgb() in ColorFunctionStyleValue.cpp.
// https://drafts.csswg.org/css-color-4/#hsl-to-rgb
fn hsl_to_absolutized_rgb(
hue_degrees: f64,
saturation_0_100: f64,
lightness_0_100: f64,
alpha_0_1: f64,
) -> StyleValueData {
let mut hue = hue_degrees % 360.0;
if hue < 0.0 {
hue += 360.0;
}
let saturation = (saturation_0_100 / 100.0).clamp(0.0, 1.0);
let lightness = (lightness_0_100 / 100.0).clamp(0.0, 1.0);
let to_rgb = |offset: f64| {
let k = (offset + hue / 30.0) % 12.0;
let a = saturation * lightness.min(1.0 - lightness);
lightness - a * (-1.0f64).max((k - 3.0).min(9.0 - k).min(1.0))
};
let r = to_rgb(0.0);
let g = to_rgb(8.0);
let b = to_rgb(4.0);
rgb_color_function(
(r * 255.0).clamp(0.0, 255.0),
(g * 255.0).clamp(0.0, 255.0),
(b * 255.0).clamp(0.0, 255.0),
alpha_0_1.clamp(0.0, 1.0),
COLOR_SYNTAX_LEGACY,
)
}
/// Port of hwb_to_absolutized_rgb() in ColorFunctionStyleValue.cpp, including its
/// single-precision arithmetic.
// https://drafts.csswg.org/css-color-4/#hwb-to-rgb
fn hwb_to_absolutized_rgb(
hue_degrees: f64,
whiteness_0_100: f64,
blackness_0_100: f64,
alpha_0_1: f64,
) -> StyleValueData {
// https://drafts.csswg.org/css-color-4/#the-hwb-notation
// Values outside of these ranges are not invalid; hue angles outside the range [0,360) will be normalized to
// that range and values of white and black which sum to 100% or greater will produce achromatic colors as
// described below.
// NB: The handling of negative white or black is unspecified, so they are clamped to 0%.
let whiteness = (whiteness_0_100 / 100.0).max(0.0) as f32;
let blackness = (blackness_0_100 / 100.0).max(0.0) as f32;
if whiteness + blackness >= 1.0 {
// The gray channel value is shared across the three slots, like the C++ code.
let gray = retain_new(StyleValueData::Number {
value: f64::from((whiteness / (whiteness + blackness) * 255.0).clamp(0.0, 255.0)),
});
return StyleValueData::ColorFunction(StyleValueBox::new(ColorFunctionPayload {
color_base: ColorBase {
has_color_type: true,
color_type: crate::css::color_conversion::RGB,
color_syntax: COLOR_SYNTAX_LEGACY,
},
channel_0: gray.clone_retained(),
channel_1: gray.clone_retained(),
channel_2: gray,
alpha: retain_new(StyleValueData::Number {
value: alpha_0_1.clamp(0.0, 1.0),
}),
has_name: false,
name: CssString::none(),
origin_color: retained_null(),
}));
}
let mut hue = (hue_degrees as f32) % 360.0;
if hue < 0.0 {
hue += 360.0;
}
let hue_to_rgb = |offset: f32| {
let k = (offset + hue / 30.0) % 12.0;
0.5 - 0.5 * (-1.0f32).max((k - 3.0).min(9.0 - k).min(1.0))
};
let scale = 1.0 - whiteness - blackness;
let r = hue_to_rgb(0.0) * scale + whiteness;
let g = hue_to_rgb(8.0) * scale + whiteness;
let b = hue_to_rgb(4.0) * scale + whiteness;
rgb_color_function(
f64::from((r * 255.0).clamp(0.0, 255.0)),
f64::from((g * 255.0).clamp(0.0, 255.0)),
f64::from((b * 255.0).clamp(0.0, 255.0)),
alpha_0_1.clamp(0.0, 1.0),
COLOR_SYNTAX_LEGACY,
)
}
/// The computed form of an absolute rgb(), hsl() or hwb() function that keeps its color function: the same
/// function with every present component resolved to a number (hues in degrees, other hsl() and hwb()
/// components in percent, rgb() components from 0 to 255) and alpha clamped to [0, 1].
fn resolved_srgb_function_components(value: &StyleValueData) -> Option<StyleValueData> {
let StyleValueData::ColorFunction(color_function_payload) = value else {
return None;
};
let ColorFunctionPayload {
color_base,
channel_0,
channel_1,
channel_2,
alpha,
..
} = &**color_function_payload;
let descriptor = descriptor_for_color_type(color_base.color_type);
let resolve_channel = |channel: &RetainedStyleValueData, index: usize| -> Option<RetainedStyleValueData> {
let value = channel.data();
if is_none_keyword(value) {
return Some(channel.clone_retained());
}
let channel_descriptor = &descriptor.channels[index];
let mut resolved = if channel_descriptor.is_hue {
resolve_hue(value, &EMPTY_INPUT)?
} else {
resolve_with_reference_value(value, f64::from(channel_descriptor.percent_reference), &EMPTY_INPUT)?
};
if color_base.color_type == crate::css::color_conversion::RGB {
resolved = resolved.clamp(0.0, 255.0);
}
// https://drafts.csswg.org/css-color-4/#the-hsl-notation
// For historical reasons, if the saturation is less than 0% it is clamped to 0% at parsed-value time,
// before being converted to an sRGB color.
if color_base.color_type == crate::css::color_conversion::HSL && index == 1 {
resolved = resolved.max(0.0);
}
Some(retain_new(StyleValueData::Number { value: resolved }))
};
let alpha = match alpha.optional_data() {
None => retained_null(),
Some(value) if is_none_keyword(value) => alpha.clone_retained(),
Some(value) => retain_new(StyleValueData::Number {
value: resolve_alpha(value, &EMPTY_INPUT)?,
}),
};
Some(StyleValueData::ColorFunction(StyleValueBox::new(
ColorFunctionPayload {
color_base: ColorBase {
color_syntax: COLOR_SYNTAX_MODERN,
..*color_base
},
channel_0: resolve_channel(channel_0, 0)?,
channel_1: resolve_channel(channel_1, 1)?,
channel_2: resolve_channel(channel_2, 2)?,
alpha,
has_name: false,
name: CssString::none(),
origin_color: retained_null(),
},
)))
}
/// Whether a value is an rgb(), hsl() or hwb() function that is not a relative color.
fn is_absolute_srgb_function(value: &StyleValueData) -> bool {
matches!(value, StyleValueData::ColorFunction(color_function)
if color_function.color_base.has_color_type
&& matches!(
color_function.color_base.color_type,
crate::css::color_conversion::RGB | crate::css::color_conversion::HSL | crate::css::color_conversion::HWB
)
&& color_function.origin_color.optional_data().is_none())
}
/// Absolutizes an absolute rgb(), hsl() or hwb() function into the same function with resolved components.
fn absolutize_srgb_function_keeping_form(
value: &StyleValueData,
context: &AbsolutizationContext,
) -> Option<StyleValueData> {
let StyleValueData::ColorFunction(color_function_payload) = value else {
return None;
};
let ColorFunctionPayload {
color_base,
channel_0,
channel_1,
channel_2,
alpha,
..
} = &**color_function_payload;
let mut changed = false;
resolved_srgb_function_components(&StyleValueData::ColorFunction(StyleValueBox::new(
ColorFunctionPayload {
color_base: *color_base,
channel_0: absolutize_child(channel_0, context, &mut changed)?,
channel_1: absolutize_child(channel_1, context, &mut changed)?,
channel_2: absolutize_child(channel_2, context, &mut changed)?,
alpha: absolutize_child(alpha, context, &mut changed)?,
has_name: false,
name: CssString::none(),
origin_color: retained_null(),
},
)))
}
/// Port of ColorFunctionStyleValue::absolutized: relative forms recurse their channels, alpha
/// and origin; HSL and HWB resolve and convert to a legacy rgb() form; every other color
/// function recurses its channels and alpha.
fn absolutize_color_function(value: &StyleValueData, context: &AbsolutizationContext) -> Option<Absolutized> {
let StyleValueData::ColorFunction(color_function_payload) = value else {
return None;
};
let ColorFunctionPayload {
color_base,
channel_0,
channel_1,
channel_2,
alpha,
has_name,
name,
origin_color,
} = &**color_function_payload;
// The C++ absolutization reads the descriptor through the unconditional color type.
if !color_base.has_color_type {
return None;
}
let mut changed = false;
let absolutized_c1 = absolutize_child(channel_0, context, &mut changed)?;
let absolutized_c2 = absolutize_child(channel_1, context, &mut changed)?;
let absolutized_c3 = absolutize_child(channel_2, context, &mut changed)?;
let absolutized_alpha = absolutize_child(alpha, context, &mut changed)?;
// https://drafts.csswg.org/css-color-5/#relative-color
if let Some(origin) = origin_color.optional_data() {
// NB: An rgb(), hsl() or hwb() origin color keeps its color function and full precision, rather than
// computing to an 8-bit rgb() value, so that the relative color sees its exact components.
let absolutized_origin = if is_absolute_srgb_function(origin) {
changed = true;
retain_new(absolutize_srgb_function_keeping_form(origin, context)?)
} else {
absolutize_child(origin_color, context, &mut changed)?
};
let rebuilt = StyleValueData::ColorFunction(StyleValueBox::new(ColorFunctionPayload {
color_base: *color_base,
channel_0: absolutized_c1,
channel_1: absolutized_c2,
channel_2: absolutized_c3,
alpha: absolutized_alpha,
has_name: *has_name,
name: name.clone(),
origin_color: absolutized_origin,
}));
// NB: Other properties keep currentcolor unresolved until the element's own color is available.
if !(context.current_color.is_none() && value_depends_on_current_color(&rebuilt))
&& let Some(resolved) = resolve_relative_form(&rebuilt, &color_resolution_input(context))
{
return Some(Absolutized::Changed(retain_new(
crate::css::color_resolution::relative_color_computed_value_form(resolved),
)));
}
return Some(if changed {
Absolutized::Changed(retain_new(rebuilt))
} else {
Absolutized::Unchanged
});
}
let descriptor = descriptor_for_color_type(color_base.color_type);
let rebuilt = StyleValueData::ColorFunction(StyleValueBox::new(ColorFunctionPayload {
color_base: *color_base,
channel_0: absolutized_c1,
channel_1: absolutized_c2,
channel_2: absolutized_c3,
alpha: absolutized_alpha,
has_name: *has_name,
name: name.clone(),
origin_color: retained_null(),
}));
// https://drafts.csswg.org/css-color-4/#css-serialization-of-srgb
// An sRGB value with missing components keeps its color function, so that those components serialize as
// the none keyword.
if matches!(
color_base.color_type,
crate::css::color_conversion::RGB | crate::css::color_conversion::HSL | crate::css::color_conversion::HWB
) && color_function_has_missing_component(&rebuilt)
{
return Some(Absolutized::Changed(retain_new(resolved_srgb_function_components(
&rebuilt,
)?)));
}
let StyleValueData::ColorFunction(color_function_payload) = &rebuilt else {
unreachable!();
};
let ColorFunctionPayload {
channel_0: absolutized_c1,
channel_1: absolutized_c2,
channel_2: absolutized_c3,
alpha: absolutized_alpha,
..
} = &**color_function_payload;
if descriptor.absolutizes_to_rgb {
// https://drafts.csswg.org/css-color-4/#resolving-sRGB-values
let c1 = if descriptor.channels[0].is_hue {
resolve_hue(absolutized_c1.data(), &EMPTY_INPUT)
} else {
resolve_with_reference_value(
absolutized_c1.data(),
f64::from(descriptor.channels[0].percent_reference),
&EMPTY_INPUT,
)
}?;
let c2 = resolve_with_reference_value(
absolutized_c2.data(),
f64::from(descriptor.channels[1].percent_reference),
&EMPTY_INPUT,
)?;
let c3 = resolve_with_reference_value(
absolutized_c3.data(),
f64::from(descriptor.channels[2].percent_reference),
&EMPTY_INPUT,
)?;
let alpha = match absolutized_alpha.optional_data() {
Some(alpha) => resolve_alpha(alpha, &EMPTY_INPUT)?,
None => 1.0,
};
let converted = if color_base.color_type == crate::css::color_conversion::HSL {
hsl_to_absolutized_rgb(c1, c2, c3, alpha)
} else {
hwb_to_absolutized_rgb(c1, c2, c3, alpha)
};
let canonical = canonical_legacy_rgb(&converted).unwrap_or(converted);
return Some(Absolutized::Changed(retain_new(canonical)));
}
if color_base.color_type == crate::css::color_conversion::RGB
&& let Some(canonical) = canonical_legacy_rgb(&rebuilt)
{
if canonical == *value {
return Some(Absolutized::Unchanged);
}
return Some(Absolutized::Changed(retain_new(canonical)));
}
if !changed {
return Some(Absolutized::Unchanged);
}
Some(Absolutized::Changed(retain_new(rebuilt)))
}
/// Normalize the mix percentages, resolve relative color forms, and mix to a concrete color.
/// When mixing cannot complete, rebuild the color mix around its absolutized parts.
// https://drafts.csswg.org/css-color-5/#color-mix-result
fn absolutize_color_mix(value: &StyleValueData, context: &AbsolutizationContext) -> Option<Absolutized> {
let StyleValueData::ColorMix(color_mix_payload) = value else {
return None;
};
let ColorMixPayload {
color_interpolation_method,
colors,
percentages,
..
} = &**color_mix_payload;
let mut percentages_changed = false;
let absolutized_percentages = absolutize_list(percentages, context, &mut percentages_changed)?;
let specified_percentages = absolutized_percentages
.iter()
.map(|percentage| match percentage.optional_data() {
None => Some(None),
Some(value) => Some(Some(percentage_from_style_value(value)?)),
})
.collect::<Option<Vec<_>>>()?;
let input = color_resolution_input(context);
let mut method_changed = false;
let absolutized_method = absolutize_child(color_interpolation_method, context, &mut method_changed)?;
// An absent method interpolates in the rectangular Oklab space.
let default_method = StyleValueData::ColorInterpolationMethod {
is_polar: false,
color_space: RECTANGULAR_COLOR_SPACE_OKLAB,
hue_interpolation_method: 0,
};
let method = absolutized_method.optional_data().unwrap_or(&default_method);
// Resolve relative-color components before interpolation so channel-keyword references
// and `none` missing-channel markers are made visible during interpolation.
let resolved_colors: Vec<Option<StyleValueData>> = colors
.as_slice()
.iter()
.map(|color| {
if let StyleValueData::ColorFunction(color_function_payload) = color.data()
&& color_function_payload.origin_color.optional_data().is_some()
{
return resolve_relative_form(color.data(), &input);
}
None
})
.collect();
let colors_for_mix = colors
.as_slice()
.iter()
.zip(&resolved_colors)
.map(|(color, resolved)| resolved.as_ref().unwrap_or(color.data()));
// NB: Without a currentcolor to resolve against, a mix reading it keeps the mix, which the color it is used as
// resolves against the element's own color.
let reads_unknown_current_color = context.current_color.is_none()
&& colors
.as_slice()
.iter()
.any(|color| color.optional_data().is_some_and(value_depends_on_current_color));
if !reads_unknown_current_color
&& let Some(result) = calculate_a_color_mix(colors_for_mix, &specified_percentages, method, &input)
{
return Some(Absolutized::Changed(retain_new(result)));
}
// Fall back to a color-mix() over absolutized values when mixing cannot complete; currently
// that means a color relies on currentcolor.
let mut colors_changed = false;
let absolutized_colors = absolutize_list(colors, context, &mut colors_changed)?;
// NB: The percentages are kept as given, since normalizing them here would lose the alpha multiplier of a sum
// under 100%. The mix normalizes them when it resolves.
let percentages_match =
percentages
.as_slice()
.iter()
.zip(&specified_percentages)
.all(|(slot, absolutized)| match (slot.optional_data(), absolutized) {
(None, None) => true,
(Some(StyleValueData::Percentage { value }), Some(absolutized)) => value == absolutized,
_ => false,
});
if !colors_changed && percentages_match {
return Some(Absolutized::Unchanged);
}
Some(Absolutized::Changed(retain_new(StyleValueData::ColorMix(
StyleValueBox::new(ColorMixPayload {
color_base: ColorBase {
has_color_type: false,
color_type: 0,
color_syntax: COLOR_SYNTAX_MODERN,
},
color_interpolation_method: absolutized_method,
colors: RetainedStyleValueDataList::from_retained_values(absolutized_colors),
percentages: RetainedStyleValueDataList::from_retained_values(
specified_percentages
.into_iter()
.map(|percentage| match percentage {
Some(value) => retain_new(StyleValueData::Percentage { value }),
None => retained_null(),
})
.collect(),
),
}),
))))
}
/// The gradient absolutizers recurse their Rust-owned children and rebuild the retained stop
/// list in place.
fn absolutize_gradient(value: &StyleValueData, context: &AbsolutizationContext) -> Option<Absolutized> {
let mut changed = false;
let absolutize_stops = |color_stop_list: &crate::css::style_value::RetainedColorStopList,
changed: &mut bool|
-> Option<crate::css::style_value::RetainedColorStopList> {
let mut stops = Vec::with_capacity(color_stop_list.as_slice().len());
for stop in color_stop_list.as_slice() {
let [transition_hint, color, position, second_position] = stop.values();
let transition_hint = absolutize_child(transition_hint, context, changed)?;
let color = absolutize_child(color, context, changed)?;
let position = absolutize_child(position, context, changed)?;
let second_position = absolutize_child(second_position, context, changed)?;
stops.push(crate::css::style_value::RetainedColorStop::from_retained_values(
transition_hint,
color,
position,
second_position,
));
}
Some(crate::css::style_value::RetainedColorStopList::from_vec(stops))
};
match value {
StyleValueData::LinearGradient(linear_gradient_payload) => {
let LinearGradientPayload {
has_direction_value,
direction_value,
side_or_corner,
color_stop_list,
gradient_type,
repeating,
color_interpolation_method,
color_syntax,
} = &**linear_gradient_payload;
let direction_value = absolutize_child(direction_value, context, &mut changed)?;
let color_stop_list = absolutize_stops(color_stop_list, &mut changed)?;
let color_interpolation_method = absolutize_child(color_interpolation_method, context, &mut changed)?;
if changed {
Some(Absolutized::Changed(retain_new(StyleValueData::LinearGradient(
StyleValueBox::new(LinearGradientPayload {
has_direction_value: *has_direction_value,
direction_value,
side_or_corner: *side_or_corner,
color_stop_list,
gradient_type: *gradient_type,
repeating: *repeating,
color_interpolation_method,
color_syntax: *color_syntax,
}),
))))
} else {
Some(Absolutized::Unchanged)
}
}
StyleValueData::RadialGradient(radial_gradient_payload) => {
let RadialGradientPayload {
ending_shape,
webkit,
has_explicit_position,
webkit_size_keyword,
size,
position,
color_stop_list,
repeating,
color_interpolation_method,
color_syntax,
} = &**radial_gradient_payload;
let size = absolutize_child(size, context, &mut changed)?;
let position = absolutize_child(position, context, &mut changed)?;
let color_stop_list = absolutize_stops(color_stop_list, &mut changed)?;
let color_interpolation_method = absolutize_child(color_interpolation_method, context, &mut changed)?;
if changed {
Some(Absolutized::Changed(retain_new(StyleValueData::RadialGradient(
StyleValueBox::new(RadialGradientPayload {
ending_shape: *ending_shape,
webkit: *webkit,
has_explicit_position: *has_explicit_position,
webkit_size_keyword: *webkit_size_keyword,
size,
position,
color_stop_list,
repeating: *repeating,
color_interpolation_method,
color_syntax: *color_syntax,
}),
))))
} else {
Some(Absolutized::Unchanged)
}
}
StyleValueData::ConicGradient(conic_gradient_payload) => {
let ConicGradientPayload {
from_angle,
position,
color_stop_list,
repeating,
color_interpolation_method,
color_syntax,
} = &**conic_gradient_payload;
let from_angle = absolutize_child(from_angle, context, &mut changed)?;
let position = absolutize_child(position, context, &mut changed)?;
let color_stop_list = absolutize_stops(color_stop_list, &mut changed)?;
let color_interpolation_method = absolutize_child(color_interpolation_method, context, &mut changed)?;
if changed {
Some(Absolutized::Changed(retain_new(StyleValueData::ConicGradient(
StyleValueBox::new(ConicGradientPayload {
from_angle,
position,
color_stop_list,
repeating: *repeating,
color_interpolation_method,
color_syntax: *color_syntax,
}),
))))
} else {
Some(Absolutized::Unchanged)
}
}
_ => None,
}
}
/// Absolutizes a child slot whose C++ accessor substitutes a default when absent; the default
/// materializes into the rebuilt value, which always counts as a change.
fn absolutize_defaulted_child(
child: &RetainedStyleValueData,
default: fn() -> StyleValueData,
context: &AbsolutizationContext,
any_changed: &mut bool,
) -> Option<RetainedStyleValueData> {
if child.optional_data().is_none() {
*any_changed = true;
let materialized = retain_new(default());
let data = materialized.data();
return match absolutize(data, context)? {
Absolutized::Unchanged => Some(materialized.clone_retained()),
Absolutized::Changed(absolutized) => Some(absolutized),
};
}
absolutize_child(child, context, any_changed)
}
/// Port of EdgeStyleValue::absolutized via with_resolved_keywords: center becomes 50%,
/// right/bottom flip to 100% minus the offset, and remaining keywords drop, leaving an
/// offset-only edge whose offset then absolutizes.
fn absolutize_edge(value: &StyleValueData, context: &AbsolutizationContext) -> Option<Absolutized> {
use crate::css::css_enums::position_edge;
let StyleValueData::Edge { has_edge, edge, offset } = value else {
return None;
};
let resolved_offset: Option<StyleValueData> = if *has_edge && *edge == position_edge::CENTER {
Some(StyleValueData::Percentage { value: 50.0 })
} else if *has_edge && (*edge == position_edge::RIGHT || *edge == position_edge::BOTTOM) {
match offset.optional_data() {
None => Some(StyleValueData::Percentage { value: 100.0 }),
Some(offset) => Some(crate::css::calc::flipped_edge_offset(offset)?),
}
} else if offset.optional_data().is_none() {
Some(StyleValueData::Percentage { value: 0.0 })
} else {
None
};
let mut changed = *has_edge || resolved_offset.is_some();
let offset = match resolved_offset {
Some(resolved) => {
let retained = retain_new(resolved);
let mut resolved_changed = false;
absolutize_child(&retained, context, &mut resolved_changed)?
}
None => absolutize_child(offset, context, &mut changed)?,
};
if !changed {
return Some(Absolutized::Unchanged);
}
Some(Absolutized::Changed(retain_new(StyleValueData::Edge {
has_edge: false,
edge: 0,
offset,
})))
}
/// Port of number_from_style_value with an empty calc context.
pub(crate) fn number_from_value(value: &StyleValueData, percentage_basis: f64) -> Option<f64> {
match value {
StyleValueData::Number { value } => Some(*value),
StyleValueData::Percentage { value } => Some(value * 0.01 * percentage_basis),
StyleValueData::Calculated { .. } => crate::css::calc::resolve_calculated_number_without_context(value)
.or_else(|| {
crate::css::calc::resolve_calculated_percentage_without_context(value)
.map(|percentage| percentage * 0.01 * percentage_basis)
}),
_ => None,
}
}
/// Compute basic shapes through structural recursion, with xywh() and rect()
/// lowering to the equivalent inset() through 100%-minus calculations, and rect()'s auto
/// edges resolving to 0% or 100%.
fn absolutize_basic_shape(
value: &StyleValueData,
resolve: &mut impl FnMut(&RetainedStyleValueData, &mut bool) -> Option<RetainedStyleValueData>,
) -> Option<Absolutized> {
let BasicShapeData {
kind,
v0,
v1,
v2,
v3,
v4,
fill_rule,
points,
path,
commands,
} = value.basic_shape()?;
// Absolutizes a freshly built 100%-minus calculation for the inset lowering.
let flipped = |values: &[&StyleValueData],
changed: &mut bool,
resolve: &mut dyn FnMut(&RetainedStyleValueData, &mut bool) -> Option<RetainedStyleValueData>|
-> Option<RetainedStyleValueData> {
*changed = true;
let built = retain_new(crate::css::calc::one_hundred_percent_minus_value(values)?);
let mut built_changed = false;
resolve(&built, &mut built_changed)
};
// rect()'s auto edges coincide with the reference box edge: 0% for top/left,
// 100% for right/bottom.
let resolve_auto =
|side: &RetainedStyleValueData, value_of_auto: f64, changed: &mut bool| -> Option<RetainedStyleValueData> {
match side.optional_data()? {
StyleValueData::Keyword { .. } => {
*changed = true;
Some(retain_new(StyleValueData::Percentage { value: value_of_auto }))
}
_ => Some(side.clone_retained()),
}
};
match kind {
0 => {
let mut changed = false;
let top = resolve(v0, &mut changed)?;
let right = resolve(v1, &mut changed)?;
let bottom = resolve(v2, &mut changed)?;
let left = resolve(v3, &mut changed)?;
let border_radius = resolve(v4, &mut changed)?;
if !changed {
return Some(Absolutized::Unchanged);
}
Some(Absolutized::Changed(retain_new(StyleValueData::BasicShape {
shape: OwnedBasicShapeData::new(BasicShapeData {
kind: 0,
v0: top,
v1: right,
v2: bottom,
v3: left,
v4: border_radius,
fill_rule: *fill_rule,
points: points.clone(),
path: path.clone(),
commands: crate::css::style_value::ShapeCommands::default(),
}),
})))
}
1 | 2 => {
// xywh(x y w h) is inset(y calc(100% - x - w) calc(100% - y - h) x);
// rect(t r b l) is inset(t calc(100% - r) calc(100% - b) l).
let mut changed = true;
let (top, right, bottom, left) = if *kind == 1 {
let x = v0.optional_data()?;
let y = v1.optional_data()?;
let width = v2.optional_data()?;
let height = v3.optional_data()?;
(
resolve(v1, &mut changed)?,
flipped(&[x, width], &mut changed, resolve)?,
flipped(&[y, height], &mut changed, resolve)?,
resolve(v0, &mut changed)?,
)
} else {
let mut auto_changed = false;
let top = resolve_auto(v0, 0.0, &mut auto_changed)?;
let right = resolve_auto(v1, 100.0, &mut auto_changed)?;
let bottom = resolve_auto(v2, 100.0, &mut auto_changed)?;
let left = resolve_auto(v3, 0.0, &mut auto_changed)?;
let mut child_changed = false;
(
resolve(&top, &mut child_changed)?,
flipped(&[right.optional_data()?], &mut child_changed, resolve)?,
flipped(&[bottom.optional_data()?], &mut child_changed, resolve)?,
resolve(&left, &mut child_changed)?,
)
};
let mut radius_changed = false;
let border_radius = resolve(v4, &mut radius_changed)?;
let _ = changed;
Some(Absolutized::Changed(retain_new(StyleValueData::BasicShape {
shape: OwnedBasicShapeData::new(BasicShapeData {
kind: 0,
v0: top,
v1: right,
v2: bottom,
v3: left,
v4: border_radius,
fill_rule: *fill_rule,
points: points.clone(),
path: path.clone(),
commands: crate::css::style_value::ShapeCommands::default(),
}),
})))
}
3 | 4 => {
let mut changed = false;
let radius = resolve(v0, &mut changed)?;
let position = resolve(v1, &mut changed)?;
if !changed {
return Some(Absolutized::Unchanged);
}
Some(Absolutized::Changed(retain_new(StyleValueData::BasicShape {
shape: OwnedBasicShapeData::new(BasicShapeData {
kind: *kind,
v0: radius,
v1: position,
v2: v2.clone_retained(),
v3: v3.clone_retained(),
v4: v4.clone_retained(),
fill_rule: *fill_rule,
points: points.clone(),
path: path.clone(),
commands: crate::css::style_value::ShapeCommands::default(),
}),
})))
}
// polygon() and shape() hold their coordinates as points.
5 | 7 => {
let mut changed = false;
let mut absolutized_points = Vec::with_capacity(points.as_slice().len());
// https://drafts.csswg.org/css-shapes-1/#shape-function
// A horizontal or vertical line to a side keyword draws to that position.
let keyword_as_percentage = |value: &RetainedStyleValueData, changed: &mut bool| {
let percentage = match value.optional_data() {
Some(StyleValueData::Keyword { keyword }) => match *keyword {
keyword::LEFT | keyword::TOP | keyword::X_START | keyword::Y_START => 0.0,
keyword::CENTER => 50.0,
keyword::RIGHT | keyword::BOTTOM | keyword::X_END | keyword::Y_END => 100.0,
_ => return value.clone_retained(),
},
_ => return value.clone_retained(),
};
*changed = true;
retain_new(StyleValueData::Percentage { value: percentage })
};
// NB: Drop resolved position wrappers so positions and explicit coordinate pairs have
// identical computed representations, including implicit and explicit "from origin".
let mut resolve_coordinate = |value: &RetainedStyleValueData, changed: &mut bool| {
let value = resolve(&keyword_as_percentage(value, changed), changed)?;
if let Some(StyleValueData::Edge {
has_edge: false,
offset,
..
}) = value.optional_data()
{
*changed = true;
Some(offset.clone_retained())
} else {
Some(value)
}
};
for point in points.as_slice() {
let [x, y] = point.values();
let x = resolve_coordinate(x, &mut changed)?;
let y = resolve_coordinate(y, &mut changed)?;
absolutized_points.push(crate::css::style_value::RetainedShapePoint::from_retained_values(x, y));
}
if !changed {
return Some(Absolutized::Unchanged);
}
Some(Absolutized::Changed(retain_new(StyleValueData::BasicShape {
shape: OwnedBasicShapeData::new(BasicShapeData {
kind: *kind,
v0: v0.clone_retained(),
v1: v1.clone_retained(),
v2: v2.clone_retained(),
v3: v3.clone_retained(),
v4: v4.clone_retained(),
fill_rule: *fill_rule,
points: crate::css::style_value::RetainedShapePointList::from_vec(absolutized_points),
path: path.clone(),
commands: commands.clone(),
}),
})))
}
_ => Some(Absolutized::Unchanged),
}
}
fn canonicalize_linear_easing_control_points(
stops: Vec<crate::css::style_value::RetainedLinearEasingStop>,
) -> Option<(Vec<crate::css::style_value::RetainedLinearEasingStop>, bool)> {
struct ControlPoint {
output: RetainedStyleValueData,
original_input: RetainedStyleValueData,
input: Option<f64>,
}
let mut control_points = stops
.into_iter()
.map(|stop| {
let [output, input] = stop.values();
let resolved_input = match input.optional_data() {
Some(input) => Some(number_from_value(input, 1.0)?),
None => None,
};
Some(ControlPoint {
output: output.clone_retained(),
original_input: input.clone_retained(),
input: resolved_input,
})
})
.collect::<Option<Vec<_>>>()?;
// https://drafts.csswg.org/css-easing/#linear-canonicalization
// To canonicalize a linear() function’s control points, perform the following:
// 1. If the first control point lacks an input progress value, set its input progress value to 0.
if control_points.first()?.input.is_none() {
control_points.first_mut()?.input = Some(0.0);
}
// 2. If the last control point lacks an input progress value, set its input progress value to 1.
if control_points.last()?.input.is_none() {
control_points.last_mut()?.input = Some(1.0);
}
// 3. If any control point has an input progress value that is less than
// the input progress value of any preceding control point,
// set its input progress value to the largest input progress value of any preceding control point.
let mut largest_input = f64::NEG_INFINITY;
for control_point in &mut control_points {
if let Some(input) = control_point.input {
if input < largest_input {
control_point.input = Some(largest_input);
} else {
largest_input = input;
}
}
}
// 4. If any control point still lacks an input progress value,
// then for each contiguous run of such control points,
// set their input progress values so that they are evenly spaced
// between the preceding and following control points with input progress values.
let mut run_start_index: Option<usize> = None;
for index in 0..control_points.len() {
if control_points[index].input.is_some() && run_start_index.is_some() {
let run_start_index = run_start_index.take()?;
let start_input = control_points[run_start_index - 1].input?;
let end_input = control_points[index].input?;
let run_stop_count = index - run_start_index + 1;
let delta = (end_input - start_input) / run_stop_count as f64;
for run_index in 0..run_stop_count {
control_points[run_index + run_start_index - 1].input = Some(start_input + delta * run_index as f64);
}
} else if control_points[index].input.is_none() && run_start_index.is_none() {
run_start_index = Some(index);
}
}
let mut changed = false;
let stops = control_points
.into_iter()
.map(|control_point| {
let input = control_point.input?;
changed |= !matches!(
control_point.original_input.optional_data(),
Some(StyleValueData::Percentage { value }) if *value == input * 100.0
);
Some(crate::css::style_value::RetainedLinearEasingStop::from_retained_values(
control_point.output,
retain_new(StyleValueData::Percentage { value: input * 100.0 }),
))
})
.collect::<Option<Vec<_>>>()?;
Some((stops, changed))
}
fn absolutize_easing(
value: &StyleValueData,
resolve: &mut impl FnMut(&RetainedStyleValueData, &mut bool) -> Option<RetainedStyleValueData>,
) -> Option<Absolutized> {
let StyleValueData::Easing(easing_payload) = value else {
return None;
};
let EasingPayload {
kind,
linear_stops,
x1,
y1,
x2,
y2,
number_of_intervals,
step_position,
is_keyword,
} = &**easing_payload;
let mut changed = *is_keyword;
let mut stops = Vec::with_capacity(linear_stops.as_slice().len());
for stop in linear_stops.as_slice() {
let [output, input] = stop.values();
let output = resolve(output, &mut changed)?;
let input = resolve(input, &mut changed)?;
stops.push(crate::css::style_value::RetainedLinearEasingStop::from_retained_values(
output, input,
));
}
if *kind == 0 {
let (canonicalized_stops, canonicalization_changed) = canonicalize_linear_easing_control_points(stops)?;
stops = canonicalized_stops;
changed |= canonicalization_changed;
}
let x1 = resolve(x1, &mut changed)?;
let y1 = resolve(y1, &mut changed)?;
let x2 = resolve(x2, &mut changed)?;
let y2 = resolve(y2, &mut changed)?;
let number_of_intervals = resolve(number_of_intervals, &mut changed)?;
if !changed {
return Some(Absolutized::Unchanged);
}
Some(Absolutized::Changed(retain_new(StyleValueData::Easing(
StyleValueBox::new(EasingPayload {
kind: *kind,
linear_stops: crate::css::style_value::RetainedLinearEasingStopList::from_vec(stops),
x1,
y1,
x2,
y2,
number_of_intervals,
step_position: *step_position,
is_keyword: false,
}),
))))
}
/// Absolutizes a grid track entry list, recursing through repeat() entries.
fn map_grid_track_entries(
entries: &[crate::css::style_value::RetainedGridTrackEntry],
map: &mut impl FnMut(&RetainedStyleValueData) -> Option<RetainedStyleValueData>,
) -> Option<Vec<crate::css::style_value::RetainedGridTrackEntry>> {
use crate::css::style_value::RetainedGridTrackEntry;
entries
.iter()
.map(|entry| {
Some(RetainedGridTrackEntry {
kind: entry.kind,
names: entry.names.clone(),
size_value: map(&entry.size_value)?,
min_value: map(&entry.min_value)?,
max_value: map(&entry.max_value)?,
repeat_type: entry.repeat_type,
repeat_count: map(&entry.repeat_count)?,
repeat_is_subgrid: entry.repeat_is_subgrid,
repeat_preserve_line_name_sets: entry.repeat_preserve_line_name_sets,
repeat_entries: RetainedGridTrackEntryList::from_retained_entries(map_grid_track_entries(
entry.repeat_entries(),
map,
)?),
})
})
.collect()
}
/// Whether `changes` answers yes of any value in a grid track entry list, recursing through repeat() entries, or none
/// where it declines before that.
fn grid_track_entries_change(
entries: &[crate::css::style_value::RetainedGridTrackEntry],
changes: &mut impl FnMut(&RetainedStyleValueData) -> Option<bool>,
) -> Option<bool> {
for entry in entries {
if changes(&entry.size_value)?
|| changes(&entry.min_value)?
|| changes(&entry.max_value)?
|| changes(&entry.repeat_count)?
|| grid_track_entries_change(entry.repeat_entries(), changes)?
{
return Some(true);
}
}
Some(false)
}
/// Whether `changes` answers yes of any value [`map_grid_values`] maps, or none where it declines before that.
fn grid_values_change(
value: &StyleValueData,
changes: &mut impl FnMut(&RetainedStyleValueData) -> Option<bool>,
) -> Option<bool> {
match value {
StyleValueData::GridTrackPlacement(placement) => changes(&placement.value),
StyleValueData::GridTrackSizeList(list) => grid_track_entries_change(list.entries.as_slice(), changes),
_ => unreachable!(),
}
}
fn map_grid_values(
value: &StyleValueData,
map: &mut impl FnMut(&RetainedStyleValueData) -> Option<RetainedStyleValueData>,
) -> Option<StyleValueData> {
Some(match value {
StyleValueData::GridTrackPlacement(grid_track_placement_payload) => {
let GridTrackPlacementPayload {
kind,
value,
has_name,
name,
implicit_start_name,
implicit_end_name,
} = &**grid_track_placement_payload;
StyleValueData::GridTrackPlacement(StyleValueBox::new(GridTrackPlacementPayload {
kind: *kind,
value: map(value)?,
has_name: *has_name,
name: name.clone(),
implicit_start_name: implicit_start_name.clone(),
implicit_end_name: implicit_end_name.clone(),
}))
}
StyleValueData::GridTrackSizeList(grid_track_size_list_payload) => {
let GridTrackSizeListPayload {
is_subgrid,
preserve_line_name_sets,
entries,
} = &**grid_track_size_list_payload;
StyleValueData::GridTrackSizeList(StyleValueBox::new(GridTrackSizeListPayload {
is_subgrid: *is_subgrid,
preserve_line_name_sets: *preserve_line_name_sets,
entries: RetainedGridTrackEntryList::from_retained_entries(map_grid_track_entries(
entries.as_slice(),
map,
)?),
}))
}
_ => unreachable!(),
})
}
/// Canonicalizes the control points of a `linear()` easing function: resolves each one's
/// calculated values and interpolates the inputs it was not given.
pub(crate) fn canonicalize_linear_easing(value: &StyleValueData) -> RetainedStyleValueData {
match absolutize_easing(value, &mut |child, _| Some(child.clone())) {
Some(Absolutized::Changed(canonical)) => canonical,
// SAFETY: The caller's reference keeps the value alive while it gains one.
_ => unsafe {
RetainedStyleValueData::from_retained_pointer(crate::css::style_value::retain_style_value(value))
},
}
}
fn canonicalized_dimension(value: f64, unit: u8, ratios: &[f64]) -> Option<(f64, u8)> {
let canonical = ratios.iter().position(|&ratio| ratio == 1.0)? as u8;
if unit == canonical {
return None;
}
Some((value * ratios[unit as usize], canonical))
}
/// Absolutizes a style value. None means the value has no absolutized form in this context.
pub(crate) fn absolutize(value: &StyleValueData, context: &AbsolutizationContext) -> Option<Absolutized> {
use crate::css::calc::{
ANGLE_UNIT_CANONICAL_RATIOS, FREQUENCY_UNIT_CANONICAL_RATIOS, RESOLUTION_UNIT_CANONICAL_RATIOS,
TIME_UNIT_CANONICAL_RATIOS,
};
// Structural rebuild helper: absolutize each child; identity when nothing changed.
macro_rules! rebuild {
($any_changed:ident, $build:expr) => {{
if $any_changed {
Some(Absolutized::Changed(retain_new($build)))
} else {
Some(Absolutized::Unchanged)
}
}};
}
match value {
// The dimension conversions: identity when already canonical.
StyleValueData::Angle { value, unit } => {
match canonicalized_dimension(*value, *unit, &ANGLE_UNIT_CANONICAL_RATIOS) {
None => Some(Absolutized::Unchanged),
Some((value, unit)) => Some(Absolutized::Changed(retain_new(StyleValueData::Angle { value, unit }))),
}
}
StyleValueData::Time { value, unit } => {
match canonicalized_dimension(*value, *unit, &TIME_UNIT_CANONICAL_RATIOS) {
None => Some(Absolutized::Unchanged),
Some((value, unit)) => Some(Absolutized::Changed(retain_new(StyleValueData::Time { value, unit }))),
}
}
StyleValueData::Frequency { value, unit } => {
match canonicalized_dimension(*value, *unit, &FREQUENCY_UNIT_CANONICAL_RATIOS) {
None => Some(Absolutized::Unchanged),
Some((value, unit)) => Some(Absolutized::Changed(retain_new(StyleValueData::Frequency {
value,
unit,
}))),
}
}
StyleValueData::Resolution { value, unit } => {
match canonicalized_dimension(*value, *unit, &RESOLUTION_UNIT_CANONICAL_RATIOS) {
None => Some(Absolutized::Unchanged),
Some((value, unit)) => Some(Absolutized::Changed(retain_new(StyleValueData::Resolution {
value,
unit,
}))),
}
}
StyleValueData::Length { value, unit } => {
let result = absolutize_length(*value, *unit as usize, context.length);
if !result.handled {
return None;
}
if result.resolved_viewport_relative_length {
context.resolved_viewport_relative_length.set(true);
}
if !result.changed {
return Some(Absolutized::Unchanged);
}
Some(Absolutized::Changed(retain_new(StyleValueData::Length {
value: result.px,
unit: crate::css::style_compute::px_length_unit(),
})))
}
// Keywords: currentcolor computes to itself; other color keywords resolve through the
// system-color tables into a legacy rgb() form, mirroring KeywordStyleValue::absolutized
// (an unresolvable color keyword computes to itself there too); everything else is
// identity.
StyleValueData::Keyword { keyword: code } => {
if *code != keyword::CURRENTCOLOR && keyword_is_color(*code) {
let input = color_resolution_input(context);
return match to_color(value, &input) {
None => Some(Absolutized::Unchanged),
Some(color) => Some(Absolutized::Changed(retain_new(rgb_color_function(
f64::from(color.r),
f64::from(color.g),
f64::from(color.b),
f64::from(f32::from(color.a) / 255.0),
COLOR_SYNTAX_LEGACY,
)))),
};
}
Some(Absolutized::Unchanged)
}
// Structural values: recurse and rebuild only on change.
StyleValueData::Ratio(ratio_payload) => {
let RatioPayload { numerator, denominator } = &**ratio_payload;
let mut changed = false;
let numerator = absolutize_child(numerator, context, &mut changed)?;
let denominator = absolutize_child(denominator, context, &mut changed)?;
rebuild!(
changed,
StyleValueData::Ratio(StyleValueBox::new(RatioPayload { numerator, denominator }))
)
}
StyleValueData::Superellipse { parameter } => {
let mut changed = false;
let parameter = absolutize_child(parameter, context, &mut changed)?;
rebuild!(changed, StyleValueData::Superellipse { parameter })
}
StyleValueData::OpenTypeTagged(open_type_tagged_payload) => {
let OpenTypeTaggedPayload {
mode,
tag_name: tag,
packed_tag,
value,
} = &**open_type_tagged_payload;
let mut changed = false;
let value = absolutize_child(value, context, &mut changed)?;
rebuild!(
changed,
StyleValueData::OpenTypeTagged(StyleValueBox::new(OpenTypeTaggedPayload {
mode: *mode,
tag_name: tag.clone(),
packed_tag: *packed_tag,
value,
}))
)
}
StyleValueData::Function(function_payload) => {
let FunctionPayload { name, value } = &**function_payload;
let mut changed = false;
let value = absolutize_child(value, context, &mut changed)?;
rebuild!(
changed,
StyleValueData::Function(StyleValueBox::new(FunctionPayload {
name: name.clone(),
value,
}))
)
}
StyleValueData::Tuple { values } => Some(match absolutize_list_if_changed(values, context)? {
None => Absolutized::Unchanged,
Some(values) => Absolutized::Changed(retain_new(StyleValueData::Tuple {
values: RetainedStyleValueDataList::from_retained_values(values),
})),
}),
StyleValueData::ValueList {
values,
separator,
collapsible,
} => Some(match absolutize_list_if_changed(values, context)? {
None => Absolutized::Unchanged,
Some(values) => Absolutized::Changed(retain_new(StyleValueData::ValueList {
values: RetainedStyleValueDataList::from_retained_values(values),
separator: *separator,
collapsible: *collapsible,
})),
}),
StyleValueData::Content(content_payload) => {
let ContentPayload { content, alt_text } = &**content_payload;
let mut changed = false;
let content = absolutize_child(content, context, &mut changed)?;
let alt_text = absolutize_child(alt_text, context, &mut changed)?;
rebuild!(
changed,
StyleValueData::Content(StyleValueBox::new(ContentPayload { content, alt_text }))
)
}
StyleValueData::Rect(rect_payload) => {
let RectPayload {
top,
right,
bottom,
left,
} = &**rect_payload;
let mut changed = false;
let top = absolutize_child(top, context, &mut changed)?;
let right = absolutize_child(right, context, &mut changed)?;
let bottom = absolutize_child(bottom, context, &mut changed)?;
let left = absolutize_child(left, context, &mut changed)?;
rebuild!(
changed,
StyleValueData::Rect(StyleValueBox::new(RectPayload {
top,
right,
bottom,
left
}))
)
}
StyleValueData::BorderImageSlice(border_image_slice_payload) => {
let BorderImageSlicePayload {
top,
right,
bottom,
left,
fill,
} = &**border_image_slice_payload;
let mut changed = false;
let top = absolutize_child(top, context, &mut changed)?;
let right = absolutize_child(right, context, &mut changed)?;
let bottom = absolutize_child(bottom, context, &mut changed)?;
let left = absolutize_child(left, context, &mut changed)?;
rebuild!(
changed,
StyleValueData::BorderImageSlice(StyleValueBox::new(BorderImageSlicePayload {
top,
right,
bottom,
left,
fill: *fill,
}))
)
}
StyleValueData::BorderRadius(border_radius_payload) => {
let BorderRadiusPayload {
is_elliptical,
horizontal_radius,
vertical_radius,
} = &**border_radius_payload;
let mut changed = false;
let horizontal_radius = absolutize_child(horizontal_radius, context, &mut changed)?;
let vertical_radius = absolutize_child(vertical_radius, context, &mut changed)?;
rebuild!(
changed,
StyleValueData::BorderRadius(StyleValueBox::new(BorderRadiusPayload {
is_elliptical: *is_elliptical,
horizontal_radius,
vertical_radius,
}))
)
}
StyleValueData::BorderRadiusRect(border_radius_rect_payload) => {
let BorderRadiusRectPayload {
top_left,
top_right,
bottom_right,
bottom_left,
} = &**border_radius_rect_payload;
let mut changed = false;
let top_left = absolutize_child(top_left, context, &mut changed)?;
let top_right = absolutize_child(top_right, context, &mut changed)?;
let bottom_right = absolutize_child(bottom_right, context, &mut changed)?;
let bottom_left = absolutize_child(bottom_left, context, &mut changed)?;
rebuild!(
changed,
StyleValueData::BorderRadiusRect(StyleValueBox::new(BorderRadiusRectPayload {
top_left,
top_right,
bottom_right,
bottom_left,
}))
)
}
StyleValueData::BackgroundSize(background_size_payload) => {
let BackgroundSizePayload { size_x, size_y } = &**background_size_payload;
let mut changed = false;
let size_x = absolutize_child(size_x, context, &mut changed)?;
let size_y = absolutize_child(size_y, context, &mut changed)?;
rebuild!(
changed,
StyleValueData::BackgroundSize(StyleValueBox::new(BackgroundSizePayload { size_x, size_y }))
)
}
StyleValueData::ScrollbarColor(scrollbar_color_payload) => {
let ScrollbarColorPayload {
thumb_color,
track_color,
} = &**scrollbar_color_payload;
let mut changed = false;
let thumb_color = absolutize_child(thumb_color, context, &mut changed)?;
let track_color = absolutize_child(track_color, context, &mut changed)?;
rebuild!(
changed,
StyleValueData::ScrollbarColor(StyleValueBox::new(ScrollbarColorPayload {
thumb_color,
track_color
}))
)
}
StyleValueData::Shadow(shadow_payload) => {
let ShadowPayload {
shadow_type,
color,
offset_x,
offset_y,
blur_radius,
spread_distance,
placement,
} = &**shadow_payload;
// The C++ absolutization reads through the defaulting accessors, so absent color,
// blur and spread slots materialize as currentcolor and zero lengths.
let mut changed = false;
let color = absolutize_defaulted_child(color, currentcolor_keyword, context, &mut changed)?;
let offset_x = absolutize_child(offset_x, context, &mut changed)?;
let offset_y = absolutize_child(offset_y, context, &mut changed)?;
let blur_radius = absolutize_defaulted_child(blur_radius, zero_px_length, context, &mut changed)?;
let spread_distance = absolutize_defaulted_child(spread_distance, zero_px_length, context, &mut changed)?;
rebuild!(
changed,
StyleValueData::Shadow(StyleValueBox::new(ShadowPayload {
shadow_type: *shadow_type,
color,
offset_x,
offset_y,
blur_radius,
spread_distance,
placement: *placement,
}))
)
}
StyleValueData::FontStyle {
font_style,
angle_value,
} => {
let mut changed = false;
let angle_value = absolutize_child(angle_value, context, &mut changed)?;
rebuild!(
changed,
StyleValueData::FontStyle {
font_style: *font_style,
angle_value,
}
)
}
StyleValueData::TextIndent {
length_percentage,
hanging,
each_line,
} => {
let mut changed = false;
let length_percentage = absolutize_child(length_percentage, context, &mut changed)?;
rebuild!(
changed,
StyleValueData::TextIndent {
length_percentage,
hanging: *hanging,
each_line: *each_line,
}
)
}
StyleValueData::OverflowClipMargin {
has_visual_box,
visual_box,
offset,
} => {
let mut changed = false;
let offset = absolutize_child(offset, context, &mut changed)?;
rebuild!(
changed,
StyleValueData::OverflowClipMargin {
has_visual_box: *has_visual_box,
visual_box: *visual_box,
offset,
}
)
}
StyleValueData::RadialSize(radial_size_payload) => {
let RadialSizePayload {
component_count,
is_extent_0,
extent_0,
value_0,
is_extent_1,
extent_1,
value_1,
} = &**radial_size_payload;
let mut changed = false;
let value_0 = absolutize_child(value_0, context, &mut changed)?;
let value_1 = absolutize_child(value_1, context, &mut changed)?;
rebuild!(
changed,
StyleValueData::RadialSize(StyleValueBox::new(RadialSizePayload {
component_count: *component_count,
is_extent_0: *is_extent_0,
extent_0: *extent_0,
value_0,
is_extent_1: *is_extent_1,
extent_1: *extent_1,
value_1,
}))
)
}
StyleValueData::Transformation(transformation_payload) => {
let TransformationPayload {
property,
transform_function,
values: original_values,
matrix_values,
..
} = &**transformation_payload;
let mut changed = false;
let mut values = absolutize_list(original_values, context, &mut changed)?;
// https://drafts.csswg.org/css-viewport/#zoom-property
// NB: The translation of a matrix is a length given in pixels, which zoom applies to as it does to a
// <length>.
let translation = match *transform_function {
crate::css::serialize::transform_function::MATRIX => 4..6,
crate::css::serialize::transform_function::MATRIX3D => 12..15,
_ => 0..0,
};
let zoom = context.length.zoom;
if zoom != 1.0 && !translation.is_empty() && values.len() >= translation.end {
for value in &mut values[translation] {
if let Some(StyleValueData::Number { value: number }) = value.optional_data() {
*value = retain_new(StyleValueData::Number { value: number * zoom });
changed = true;
}
}
}
let mut retained_matrix_values = crate::css::style_value::map_transform_matrix_values(
original_values.as_slice(),
&values,
matrix_values.as_slice(),
)
.as_slice()
.to_vec();
let original_values = original_values.as_slice();
let parameters = crate::css::serialize::TRANSFORM_FUNCTION_PARAMETER_TYPES[*transform_function as usize];
for (index, original) in original_values.iter().enumerate() {
if parameters.get(index) != Some(&crate::css::table_group_builder::TRANSFORM_PARAMETER_ANGLE)
|| !matches!(original.data(), StyleValueData::Angle { value, .. } if value.is_finite())
|| (!retained_matrix_values.is_empty()
&& retained_matrix_values[index].data() != values[index].data())
{
continue;
}
let precise = crate::css::table_group_builder::transform_angle_radians(original.data()) as f32;
let canonical = crate::css::table_group_builder::transform_angle_radians(values[index].data()) as f32;
if precise.to_bits() != canonical.to_bits() {
if retained_matrix_values.is_empty() {
retained_matrix_values = values.clone();
}
retained_matrix_values[index] = original.clone_retained();
}
}
let retained_matrix_values = RetainedStyleValueDataList::from_retained_values(retained_matrix_values);
changed |= retained_matrix_values != *matrix_values;
rebuild!(
changed,
StyleValueData::Transformation(StyleValueBox::new(TransformationPayload {
property: *property,
transform_function: *transform_function,
values: RetainedStyleValueDataList::from_retained_values(values),
matrix_values: retained_matrix_values,
}))
)
}
StyleValueData::Filter {
kind,
color_operation,
value,
} => {
// Color filters resolve their amount to a number, clamped to [0, 1] for
// grayscale, invert, opacity and sepia, exactly like the C++ absolutization.
if *kind == 3 {
let inner = value.optional_data()?;
let mut changed = false;
let absolutized = absolutize_child(value, context, &mut changed)?;
let mut amount = number_from_value(absolutized.optional_data()?, 1.0)?;
if matches!(color_operation, 2 | 3 | 4 | 6) {
amount = amount.clamp(0.0, 1.0);
}
if !changed && matches!(inner, StyleValueData::Number { value } if *value == amount) {
return Some(Absolutized::Unchanged);
}
return Some(Absolutized::Changed(retain_new(StyleValueData::Filter {
kind: *kind,
color_operation: *color_operation,
value: retain_new(StyleValueData::Number { value: amount }),
})));
}
let mut changed = false;
// drop-shadow hand-rolls its shadow absolutization in C++: color and blur
// materialize their defaults, but spread stays absent.
let value = if *kind == 1 {
let Some(StyleValueData::Shadow(shadow_payload)) = value.optional_data() else {
return None;
};
let ShadowPayload {
shadow_type,
color,
offset_x,
offset_y,
blur_radius,
spread_distance,
placement,
} = &**shadow_payload;
let color = absolutize_defaulted_child(color, currentcolor_keyword, context, &mut changed)?;
let offset_x = absolutize_child(offset_x, context, &mut changed)?;
let offset_y = absolutize_child(offset_y, context, &mut changed)?;
let blur_radius = absolutize_defaulted_child(blur_radius, zero_px_length, context, &mut changed)?;
if changed {
retain_new(StyleValueData::Shadow(StyleValueBox::new(ShadowPayload {
shadow_type: *shadow_type,
color,
offset_x,
offset_y,
blur_radius,
spread_distance: spread_distance.clone_retained(),
placement: *placement,
})))
} else {
value.clone_retained()
}
} else {
absolutize_child(value, context, &mut changed)?
};
rebuild!(
changed,
StyleValueData::Filter {
kind: *kind,
color_operation: *color_operation,
value,
}
)
}
StyleValueData::Calculated { .. } => {
// Thread a local tracking flag so viewport-relative lengths resolved inside the
// calculation report the dependency exactly like the C++ path.
let mut tracked = false;
let mut calc_length_context = *context.length;
calc_length_context.resolved_viewport_relative_length = &raw mut tracked;
let outcome = crate::css::calc::absolutize_calculation_value(
value,
&calc_length_context,
context.tree_counting,
context.random_base_values,
);
if tracked {
context.resolved_viewport_relative_length.set(true);
}
match outcome? {
crate::css::calc::AbsolutizedCalculation::Unchanged => Some(Absolutized::Unchanged),
crate::css::calc::AbsolutizedCalculation::Percentage(percentage) => {
Some(Absolutized::Changed(retain_new(StyleValueData::Percentage {
value: percentage,
})))
}
crate::css::calc::AbsolutizedCalculation::Value(new_value) => {
Some(Absolutized::Changed(retain_new(new_value)))
}
}
}
StyleValueData::Edge { .. } => absolutize_edge(value, context),
StyleValueData::Anchor { .. } | StyleValueData::AnchorSize { .. } => {
let mut tracked = false;
let mut calc_length_context = *context.length;
calc_length_context.resolved_viewport_relative_length = &raw mut tracked;
let outcome = crate::css::calc::absolutize_anchor_function(
value,
&calc_length_context,
context.tree_counting,
context.random_base_values,
);
if tracked {
context.resolved_viewport_relative_length.set(true);
}
match outcome? {
None => Some(Absolutized::Unchanged),
Some(absolutized) => Some(Absolutized::Changed(retain_new(absolutized))),
}
}
StyleValueData::Position(position_payload) => {
let PositionPayload { edge_x, edge_y } = &**position_payload;
let mut changed = false;
let edge_x = absolutize_child(edge_x, context, &mut changed)?;
let edge_y = absolutize_child(edge_y, context, &mut changed)?;
rebuild!(
changed,
StyleValueData::Position(StyleValueBox::new(PositionPayload { edge_x, edge_y }))
)
}
StyleValueData::BasicShape { .. } => {
absolutize_basic_shape(value, &mut |child, changed| absolutize_child(child, context, changed))
}
StyleValueData::Ray(ray_payload) => {
let RayPayload {
size,
contain,
angle,
position,
} = &**ray_payload;
let mut changed = false;
let angle = absolutize_child(angle, context, &mut changed)?;
let position = absolutize_child(position, context, &mut changed)?;
rebuild!(
changed,
StyleValueData::Ray(StyleValueBox::new(RayPayload {
size: *size,
contain: *contain,
angle,
position,
}))
)
}
StyleValueData::Cursor(cursor_payload) => {
let CursorPayload { image, x, y } = &**cursor_payload;
let mut changed = false;
let image = absolutize_child(image, context, &mut changed)?;
let x = absolutize_child(x, context, &mut changed)?;
let y = absolutize_child(y, context, &mut changed)?;
rebuild!(
changed,
StyleValueData::Cursor(StyleValueBox::new(CursorPayload { image, x, y }))
)
}
StyleValueData::Easing { .. } => {
absolutize_easing(value, &mut |child, changed| absolutize_child(child, context, changed))
}
StyleValueData::ImageSet(image_set_payload) => {
let ImageSetPayload { options } = &**image_set_payload;
let mut changed = false;
let mut absolutized_options = Vec::with_capacity(options.as_slice().len());
for option in options.as_slice() {
let [image, resolution] = option.values();
let image = absolutize_child(image, context, &mut changed)?;
let resolution = absolutize_child(resolution, context, &mut changed)?;
absolutized_options.push(option.with_values(image, resolution));
}
rebuild!(
changed,
StyleValueData::ImageSet(StyleValueBox::new(ImageSetPayload {
options: crate::css::style_value::RetainedImageSetOptionList::from_vec(absolutized_options),
}))
)
}
StyleValueData::CounterDefinitions(counter_definitions_payload) => {
let CounterDefinitionsPayload { counter_definitions } = &**counter_definitions_payload;
let mut changed = false;
let mut definitions = Vec::with_capacity(counter_definitions.as_slice().len());
for definition in counter_definitions.as_slice() {
let value = absolutize_child(definition.value(), context, &mut changed)?;
definitions.push(definition.with_value(value));
}
rebuild!(
changed,
StyleValueData::CounterDefinitions(StyleValueBox::new(CounterDefinitionsPayload {
counter_definitions: crate::css::style_value::RetainedCounterDefinitionList::from_vec(definitions),
}))
)
}
StyleValueData::CounterStyleSystem(counter_style_system_payload) => {
let CounterStyleSystemPayload {
kind,
system,
first_symbol,
name,
} = &**counter_style_system_payload;
let mut changed = false;
let first_symbol = absolutize_child(first_symbol, context, &mut changed)?;
rebuild!(
changed,
StyleValueData::CounterStyleSystem(StyleValueBox::new(CounterStyleSystemPayload {
kind: *kind,
system: *system,
first_symbol,
name: name.clone(),
}))
)
}
StyleValueData::GridTrackPlacement { .. } | StyleValueData::GridTrackSizeList { .. } => {
// NB: Tracks and lines are mostly absolute already, which a walk answers without building a list.
if !grid_values_change(value, &mut |child| {
let Some(data) = child.optional_data() else {
return Some(false);
};
Some(matches!(absolutize(data, context)?, Absolutized::Changed(_)))
})? {
return Some(Absolutized::Unchanged);
}
let mut changed = false;
let mapped = map_grid_values(value, &mut |child| absolutize_child(child, context, &mut changed))?;
rebuild!(changed, mapped)
}
// Tree-counting functions resolve from immutable sibling facts captured before the
// longhand drive. Random sharing and image base URLs still need live external state.
StyleValueData::TreeCountingFunction {
function,
computed_type,
} => {
let (sibling_count, sibling_index) = context.tree_counting?;
let value = if *function == 0 { sibling_count } else { sibling_index };
Some(Absolutized::Changed(retain_new(if *computed_type == 0 {
StyleValueData::Number { value: value as f64 }
} else {
StyleValueData::Integer {
value: i32::try_from(value).expect("sibling count exceeds CSS integer range"),
}
})))
}
StyleValueData::Url(url_payload) => {
let UrlPayload {
url,
url_type,
modifiers,
} = &**url_payload;
// https://drafts.csswg.org/css-values-4/#local-urls
// When serializing a url() with the local url flag set, it must serialize as just the fragment.
if url.is_empty() || url.is_fragment() {
return Some(Absolutized::Unchanged);
}
// https://drafts.csswg.org/css-values-4/#relative-urls
// When a <url> appears in the computed value of a property, it is resolved to an absolute URL.
// The computed value of a URL that the UA cannot resolve to an absolute URL is the specified value.
let resolved_url = liburl_rust::basic_parse(url.url_input(), liburl_rust::BasicParseOptions::new())
.or_else(|| {
let base_url = context
.style_sheet_resource_context
.map(|resource_context| resource_context.base_url)
.filter(|base_url| !base_url.is_empty())
.unwrap_or(context.document_base_url);
let base_url = std::str::from_utf8(base_url).ok()?;
let base_url = liburl_rust::basic_parse(base_url, liburl_rust::BasicParseOptions::new())?;
liburl_rust::basic_parse(
url.url_input(),
liburl_rust::BasicParseOptions::new().base_url(&base_url),
)
});
let Some(resolved_url) = resolved_url else {
return Some(Absolutized::Unchanged);
};
Some(Absolutized::Changed(retain_new(StyleValueData::Url(
StyleValueBox::new(UrlPayload {
url: crate::css::style_value::RetainedString::from_ascii(resolved_url.into()),
url_type: *url_type,
modifiers: modifiers.clone(),
}),
))))
}
StyleValueData::Image { .. } => absolutize_image(value, context),
// https://drafts.csswg.org/css-values-5/#random-caching
// If the random function's <random-value-sharing> is fixed <number>, the random base value is that number.
// Otherwise, it is the base value drawn for the function's random caching key.
StyleValueData::RandomValueSharing(random_value_sharing_payload) => {
let RandomValueSharingPayload {
fixed_value,
is_auto,
has_name,
name,
element_shared,
} = &**random_value_sharing_payload;
if fixed_value.optional_data().is_some() {
let mut changed = false;
let fixed_value = absolutize_child(fixed_value, context, &mut changed)?;
return rebuild!(
changed,
StyleValueData::RandomValueSharing(StyleValueBox::new(RandomValueSharingPayload {
fixed_value,
is_auto: *is_auto,
has_name: *has_name,
name: name.clone(),
element_shared: *element_shared,
}))
);
}
let base_value = context
.random_base_values
.iter()
.find(|base_value| std::ptr::eq(base_value.source.cast(), value))?
.value;
Some(Absolutized::Changed(retain_new(StyleValueData::RandomValueSharing(
StyleValueBox::new(RandomValueSharingPayload {
fixed_value: retain_new(StyleValueData::Number { value: base_value }),
is_auto: false,
has_name: false,
name: CssString::none(),
element_shared: false,
}),
))))
}
StyleValueData::ColorFunction { .. } => absolutize_color_function(value, context),
StyleValueData::ColorMix { .. } => absolutize_color_mix(value, context),
StyleValueData::LinearGradient { .. }
| StyleValueData::RadialGradient { .. }
| StyleValueData::ConicGradient { .. } => absolutize_gradient(value, context),
// https://drafts.csswg.org/css-color-5/#contrast-color
// A resolvable contrast-color computes to its picked foreground color; otherwise the
// inner color absolutizes in place.
StyleValueData::ContrastColor { color, .. } => {
let input = color_resolution_input(context);
if let Some(resolved) = to_color(value, &input) {
return Some(Absolutized::Changed(retain_new(rgb_color_function(
f64::from(resolved.r),
f64::from(resolved.g),
f64::from(resolved.b),
f64::from(resolved.a) / 255.0,
COLOR_SYNTAX_MODERN,
))));
}
let mut changed = false;
let color = absolutize_child(color, context, &mut changed)?;
rebuild!(
changed,
StyleValueData::ContrastColor {
color_base: ColorBase {
has_color_type: false,
color_type: 0,
color_syntax: COLOR_SYNTAX_MODERN,
},
color,
}
)
}
// https://drafts.csswg.org/css-color-5/#funcdef-light-dark
// With no scheme the value computes to itself; otherwise it collapses to the matching
// branch's absolutized value.
StyleValueData::LightDark(light_dark_payload) => {
let LightDarkPayload { light, dark, .. } = &**light_dark_payload;
let Some(scheme) = context.scheme else {
return Some(Absolutized::Unchanged);
};
let branch = if scheme == PREFERRED_COLOR_SCHEME_DARK {
dark
} else {
light
};
let mut changed = false;
let absolutized = absolutize_child(branch, context, &mut changed)?;
Some(Absolutized::Changed(absolutized))
}
StyleValueData::OpacityValue { value } => {
let inner = value.optional_data()?;
// Plain numbers strictly inside (0, 1) stay untouched, like the C++ fast path.
if matches!(inner, StyleValueData::Number { value } if *value > 0.0 && *value < 1.0) {
return Some(Absolutized::Unchanged);
}
let mut changed = false;
let absolutized = absolutize_child(value, context, &mut changed)?;
let number = number_from_value(absolutized.optional_data()?, 1.0)?;
Some(Absolutized::Changed(retain_new(StyleValueData::OpacityValue {
value: retain_new(StyleValueData::Number {
value: number.clamp(0.0, 1.0),
}),
})))
}
// Everything else is identity under the C++ dispatcher's default case.
_ => Some(Absolutized::Unchanged),
}
}
/// The facts of the element a C++ caller computes a value for, which Rust asks for only when a
/// value needs them.
#[repr(C)]
pub struct FfiElementFacts {
pub has_element: bool,
pub callback_context: *const core::ffi::c_void,
/// Fills in the container bases that the given container-relative units read, into the
/// given copy of the length resolution context.
pub fill_container_bases: unsafe extern "C" fn(*const core::ffi::c_void, u8, *mut core::ffi::c_void),
/// Writes the element's sibling count and index. False when there is no element.
pub tree_counting: unsafe extern "C" fn(*const core::ffi::c_void, &mut u64, &mut u64) -> bool,
/// Draws the random base value of a random caching key. False when there is no element.
pub random_base_value: unsafe extern "C" fn(*const core::ffi::c_void, *const u16, usize, bool, &mut f64) -> bool,
}
impl FfiElementFacts {
pub(crate) fn fill_container_bases(&self, unit_mask: u8, length: &mut FfiLengthResolutionContext) {
unsafe { (self.fill_container_bases)(self.callback_context, unit_mask, std::ptr::from_mut(length).cast()) };
}
pub(crate) fn tree_counting(&self) -> Option<(u64, u64)> {
let (mut sibling_count, mut sibling_index) = (0, 0);
unsafe { (self.tree_counting)(self.callback_context, &mut sibling_count, &mut sibling_index) }
.then_some((sibling_count, sibling_index))
}
pub(crate) fn random_base_value(&self, name: &[u16], element_shared: bool) -> Option<f64> {
let mut value = 0.0;
unsafe {
(self.random_base_value)(
self.callback_context,
name.as_ptr(),
name.len(),
element_shared,
&mut value,
)
}
.then_some(value)
}
}
/// Absolutizes a value outside the style drive, asking the element's facts for what the value
/// needs.
pub(crate) fn absolutize_with_element_facts(
value: &StyleValueData,
length: &FfiLengthResolutionContext,
scheme: Option<u8>,
document_base_url: &[u8],
facts: Option<&FfiElementFacts>,
) -> Option<Absolutized> {
let dependencies = crate::css::style_compute::collect_external_value_dependencies(value);
let mut length = *length;
let mut tree_counting = None;
let mut random_base_values = Vec::new();
if let Some(facts) = facts {
if dependencies.container_relative_length_unit_mask != 0 {
facts.fill_container_bases(dependencies.container_relative_length_unit_mask, &mut length);
}
if dependencies.uses_tree_counting_function {
tree_counting = facts.tree_counting();
}
if dependencies.has_unfixed_random_sharing {
let mut sharings = Vec::new();
crate::css::style_compute::collect_unfixed_random_sharings_in_value(value, &mut sharings);
for sharing in sharings {
// SAFETY: The value retains every sharing in it.
let (name, element_shared) = crate::css::style_compute::random_caching_key(unsafe { &*sharing });
if let Some(base_value) = facts.random_base_value(name, element_shared) {
random_base_values.push(crate::css::style_compute::FfiRandomBaseValue {
source: sharing.cast(),
value: base_value,
});
}
}
}
}
// The length context records a viewport-relative resolution through its own flag.
absolutize(
value,
&AbsolutizationContext {
length: &length,
scheme,
resolved_viewport_relative_length: Cell::new(false),
tree_counting,
random_base_values: &random_base_values,
document_base_url,
style_sheet_resource_context: None,
current_color: None,
},
)
}
/// What a C++ caller outside the style drive gives an absolutization.
#[repr(C)]
pub struct FfiAbsolutizationContext {
/// The length resolution context, as an opaque pointer since its type lives in the computed
/// values header.
pub length: *const core::ffi::c_void,
pub has_scheme: bool,
pub scheme: u8,
pub document_base_url: *const u8,
pub document_base_url_length: usize,
pub element_facts: FfiElementFacts,
}
/// Absolutizes a style value for a C++ caller outside the style drive. Returns one strong
/// reference to the new value, or null when the value computes to itself.
///
/// # Safety
/// `context`'s pointers must be valid for the call, and its callbacks must accept its callback
/// context.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_style_value_absolutize(
value: &StyleValueData,
context: &FfiAbsolutizationContext,
) -> *const StyleValueData {
let document_base_url = if context.document_base_url_length == 0 {
&[][..]
} else {
unsafe { ak::slice_from_raw_parts(context.document_base_url, context.document_base_url_length) }
};
match absolutize_with_element_facts(
value,
unsafe { &*context.length.cast::<FfiLengthResolutionContext>() },
context.has_scheme.then_some(context.scheme),
document_base_url,
Some(&context.element_facts),
) {
Some(Absolutized::Changed(new_value)) => {
let pointer = new_value.pointer();
core::mem::forget(new_value);
pointer
}
// A value whose facts are missing, like a tree-counting function without an element,
// computes to itself.
Some(Absolutized::Unchanged) | None => core::ptr::null(),
}
}
#[cfg(test)]
mod color_channel_tests {
use super::*;
#[test]
fn integral_color_channels_share_without_rounding_other_numbers() {
for channel in 0..=255_u16 {
let first = RetainedStyleValueData::from_owned(StyleValueData::Number {
value: f64::from(channel),
});
let second = RetainedStyleValueData::from_owned(StyleValueData::Number {
value: f64::from(channel),
});
assert_eq!(first.pointer(), second.pointer());
}
for value in [-0.0, -1.0, 0.5, 255.5, 256.0, f64::INFINITY, f64::NAN] {
let channel = RetainedStyleValueData::from_owned(StyleValueData::Number { value });
let StyleValueData::Number { value: actual } = channel.data() else {
panic!("a channel must remain a number");
};
assert_eq!(actual.to_bits(), value.to_bits());
}
}
}