Skip to content

Truly independent web browser

LibWeb: Resolve the values of laid out boxes in Rust

Andreas Kling083cf93d4cc9
diff --git a/Libraries/LibWeb/CSS/CSSStyleProperties.cpp b/Libraries/LibWeb/CSS/CSSStyleProperties.cpp
index 55f7a1e75d1..b070011ca54 100644
--- a/Libraries/LibWeb/CSS/CSSStyleProperties.cpp
+++ b/Libraries/LibWeb/CSS/CSSStyleProperties.cpp
@@ -335,17 +335,6 @@ static NonnullRefPtr<StyleValue const> style_value_for_length_percentage(LengthP
return length_percentage.calculated();
}
-static NonnullRefPtr<StyleValue const> style_value_for_length_percentage_or_auto(LengthPercentageOrAuto const& length_percentage)
-{
- if (length_percentage.is_auto())
- return KeywordStyleValue::create(Keyword::Auto);
- if (length_percentage.is_percentage())
- return PercentageStyleValue::create(length_percentage.percentage());
- if (length_percentage.is_length())
- return LengthStyleValue::create(length_percentage.length());
- return length_percentage.calculated();
-}
-
static NonnullRefPtr<StyleValue const> style_value_for_transform_origin(TransformOrigin const& transform_origin, Optional<CSSPixelRect> const& reference_box)
{
auto offset_in_px = [](LengthPercentage const& offset, CSSPixels reference_length) {
@@ -1104,6 +1093,10 @@ RefPtr<StyleValue const> CSSStyleProperties::style_value_for_computed_property(L
dbgln_if(LIBWEB_CSS_DEBUG, "Computed style for CSSStyleProperties without owner node was requested");
return nullptr;
}
+ if (property_id == PropertyID::Custom) {
+ dbgln_if(LIBWEB_CSS_DEBUG, "Computed style for custom properties was requested (?)");
+ return nullptr;
+ }
// https://drafts.csswg.org/css-tables-3/#table-wrapper-box
// The computed values of properties position, float, margin-*, top, right, bottom, and left on the table are used
@@ -1116,515 +1109,42 @@ RefPtr<StyleValue const> CSSStyleProperties::style_value_for_computed_property(L
}
return layout_node;
}();
-
- auto used_value_for_box = [](Layout::NodeWithStyle const& box_layout_node, Function<CSSPixels(Layout::Node const&)>&& used_value_getter) -> Optional<CSSPixels> {
- auto display = box_layout_node.display();
- if (!display.is_none() && !display.is_contents() && Painting::has_committed_box(box_layout_node))
- return used_value_getter(box_layout_node);
- return {};
- };
- auto used_value_for_property = [&layout_node, &used_value_for_box](Function<CSSPixels(Layout::Node const&)>&& used_value_getter) -> Optional<CSSPixels> {
- return used_value_for_box(layout_node, move(used_value_getter));
- };
-
- // https://drafts.csswg.org/cssom/#resolved-value-special-case-property-like-height
- // If the property applies to the element or pseudo-element and the resolved value of the display property is not
- // none or contents, then the resolved value is the used value. Otherwise the resolved value is the computed value.
- auto resolved_value_for_margin = [&principal_layout_node, &used_value_for_box](LengthPercentageOrAuto const& margin, Function<CSSPixels(Layout::Node const&)>&& used_value_getter) -> NonnullRefPtr<StyleValue const> {
- auto computed_value = [&] { return style_value_for_length_percentage_or_auto(margin); };
- auto maybe_used_value = used_value_for_box(principal_layout_node, move(used_value_getter));
- if (!maybe_used_value.has_value())
- return computed_value();
- auto const* containing_block = principal_layout_node.containing_block();
- // NB: Positioned boxes can have position-try overrides, and grid/flex items can use a specialized basis.
- if (!principal_layout_node.display().is_block_outside() || principal_layout_node.is_absolutely_positioned()
- || (containing_block && (containing_block->display().is_grid_inside() || containing_block->display().is_flex_inside())))
- return LengthStyleValue::create(Length::make_px(maybe_used_value.release_value()));
- auto resolved_length = [](double pixels) -> NonnullRefPtr<StyleValue const> {
- // NB: Retain fractional precision within the layout range, and preserve saturation outside it.
- if (pixels < CSSPixels::min_integer_value || pixels > CSSPixels::max_integer_value)
- pixels = CSSPixels::nearest_value_for(pixels).to_double();
- return LengthStyleValue::create(Length::make_px(pixels));
- };
- // INTEROP: Chrome and Safari exclude the adjustment that satisfies an over-constrained block's inline-size equation.
- if (margin.is_length())
- return resolved_length(margin.length().absolute_length_to_px_without_rounding());
- if (!margin.is_auto()) {
- if (containing_block && Painting::has_committed_box(*containing_block)) {
- auto size = Painting::content_size(*containing_block);
- auto basis = containing_block->writing_mode() == WritingMode::HorizontalTb ? size.width() : size.height();
- auto const& length_percentage = margin.length_percentage();
- if (length_percentage.is_percentage())
- return resolved_length(basis.to_double() * length_percentage.percentage().as_fraction());
- if (auto resolved = length_percentage.calculated()->resolve_length({ .percentage_basis = Length::make_px(basis) }); resolved.has_value())
- return resolved_length(resolved->absolute_length_to_px_without_rounding());
- }
- }
- return LengthStyleValue::create(Length::make_px(maybe_used_value.release_value()));
- };
-
- auto used_size_for_property = [&layout_node, &used_value_for_property]<typename ContentBoxGetter, typename BorderBoxGetter>(ContentBoxGetter content_box_getter, BorderBoxGetter border_box_getter) -> Optional<CSSPixels> {
- return used_value_for_property([&layout_node, content_box_getter, border_box_getter](Layout::Node const& box_layout_node) {
- if (layout_node.box_sizing() == BoxSizing::BorderBox)
- return border_box_getter(box_layout_node);
- return content_box_getter(box_layout_node);
- });
- };
-
- auto& element = owner_node()->element();
- auto pseudo_element = owner_node()->pseudo_element();
-
- // https://drafts.csswg.org/cssom/#resolved-value-special-case-property-like-top
- enum class InsetAxis : u8 {
- Horizontal,
- Vertical,
- };
- auto resolved_value_for_inset = [&principal_layout_node](LengthPercentageOrAuto const& side, LengthPercentageOrAuto const& opposite_side, InsetAxis axis, Function<CSSPixels(Layout::Node const&)>&& used_value_getter) -> NonnullRefPtr<StyleValue const> {
- auto computed_value = [&] { return style_value_for_length_percentage_or_auto(side); };
-
- auto display = principal_layout_node.display();
- if (!principal_layout_node.is_positioned() || display.is_none() || display.is_contents() || !Painting::has_committed_box(principal_layout_node))
- return computed_value();
-
- // NB: The used value of a fixed length is the length itself. Taking it from the computed value keeps
- // the precision that layout units would lose. Layout saturates lengths beyond the range of layout
- // units, so those are reported as saturated.
- if (side.is_length()) {
- auto pixels = side.length().absolute_length_to_px_without_rounding();
- if (pixels >= CSSPixels::min_integer_value && pixels <= CSSPixels::max_integer_value)
- return computed_value();
- return LengthStyleValue::create(Length::make_px(CSSPixels::nearest_value_for(pixels)));
- }
-
- auto absolutized_against = [&](CSSPixels percentage_basis) -> NonnullRefPtr<StyleValue const> {
- auto const& length_percentage = side.length_percentage();
- if (length_percentage.is_percentage())
- return LengthStyleValue::create(Length::make_px(percentage_basis.to_double() * length_percentage.percentage().as_fraction()));
- return LengthStyleValue::create(Length::make_px(length_percentage.resolved(percentage_basis).absolute_length_to_px_without_rounding()));
- };
- auto size_in_axis = [axis](CSSPixelSize size) { return axis == InsetAxis::Horizontal ? size.width() : size.height(); };
-
- // https://drafts.csswg.org/css-position/#insets
- // For sticky positioned boxes, the inset is instead relative to the relevant scrollport's size.
- if (principal_layout_node.is_sticky_position()) {
- // NB: Sticky positioning leaves an auto inset unconstrained, so its used value stays auto.
- if (side.is_auto())
- return computed_value();
- // NB: This uses the same scrollport size as the sticky constraints: the content box of the nearest
- // scroll container, or of the viewport.
- Layout::Box const* scroll_container = principal_layout_node.containing_block();
- while (scroll_container && !scroll_container->is_scroll_container())
- scroll_container = scroll_container->containing_block();
- if (!scroll_container || !Painting::has_committed_box(*scroll_container))
- return computed_value();
- return absolutized_against(size_in_axis(Painting::content_size(*scroll_container)));
- }
-
- // https://drafts.csswg.org/css-position/#relpos-insets
- // If neither is auto, the position is over-constrained;
- // NB: The resolved value is then the computed value, absolutized against the containing block.
- // INTEROP: Percentages are absolutized rather than serialized as-is, to match other browsers.
- if (principal_layout_node.position() == Positioning::Relative && !side.is_auto() && !opposite_side.is_auto()) {
- auto const* containing_block = principal_layout_node.containing_block();
- if (!containing_block || !Painting::has_committed_box(*containing_block))
- return computed_value();
- return absolutized_against(size_in_axis(Painting::content_size(*containing_block)));
- }
-
- return LengthStyleValue::create(Length::make_px(used_value_getter(principal_layout_node)));
- };
-
- auto get_computed_value = [&element, pseudo_element](PropertyID property_id) -> NonnullRefPtr<StyleValue const> {
- auto style = element.computed_style(pseudo_element);
- VERIFY(style);
- return style->computed_style_value(property_id).release_nonnull();
- };
- auto color_resolution_style = ColorResolutionStyle::for_layout_node(layout_node);
-
- // A logical property maps by the element's own writing mode and direction, which its box may not show yet: a box
- // awaiting the layout tree update that replaces it keeps the style it was built for.
- if (property_is_logical_alias(property_id)) {
- auto style = element.computed_style(pseudo_element);
- VERIFY(style);
- return style_value_for_computed_property(
- layout_node,
- map_logical_alias_to_physical_property(property_id, LogicalAliasMappingContext { style->writing_mode(), style->direction() }));
+ // NB: Only the resolved values of the margins and the insets depend on the containing block. A logical alias may be
+ // one of them, as it only maps to its physical property when the value is resolved.
+ bool may_be_margin_or_inset = property_is_logical_alias(property_id) || first_is_one_of(property_id, PropertyID::MarginTop, PropertyID::MarginRight, PropertyID::MarginBottom, PropertyID::MarginLeft, PropertyID::Top, PropertyID::Right, PropertyID::Bottom, PropertyID::Left);
+ auto const* containing_block = may_be_margin_or_inset ? principal_layout_node.containing_block() : nullptr;
+ // NB: Only the insets of a sticky box are relative to a scroll container.
+ Layout::NodeWithStyle const* scroll_container = nullptr;
+ if (may_be_margin_or_inset && principal_layout_node.is_sticky_position()) {
+ scroll_container = containing_block;
+ while (scroll_container && !scroll_container->is_scroll_container())
+ scroll_container = scroll_container->containing_block();
}
- // A limited number of properties have special rules for producing their "resolved value".
- // We also have to manually construct shorthands from their longhands here.
- // Everything else uses the computed value.
- // https://drafts.csswg.org/cssom/#resolved-values
-
- // AD-HOC: We don't resolve logical properties here as we have already handled above
- // The resolved value for a given longhand property can be determined as follows:
- switch (property_id) {
- // -> background-color
- // -> border-block-end-color
- // -> border-block-start-color
- // -> border-bottom-color
- // -> border-inline-end-color
- // -> border-inline-start-color
- // -> border-left-color
- // -> border-right-color
- // -> border-top-color
- // -> box-shadow
- // -> caret-color
- // -> color
- // -> outline-color
- // -> A resolved value special case property like color defined in another specification
- // The resolved value is the used value.
- case PropertyID::BackgroundColor: {
- auto const* background_values = element.style_group<ComputedValues::BackgroundValues>(pseudo_element);
- VERIFY(background_values);
- auto const& handle = background_values->background_color_style_value;
- VERIFY(handle.pointer);
- auto style_value = StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(
- static_cast<StyleValueFFI::StyleValueData const*>(handle.pointer)));
- return resolve_color_style_value(
- *style_value,
- background_values->background_color_value(element.style_group<ComputedValues::InheritedTextValues>(pseudo_element)->color_value()),
- color_resolution_style);
- }
- case PropertyID::BorderBottomColor:
- return resolve_color_style_value(*get_computed_value(property_id), layout_node.border_bottom().color, color_resolution_style);
- case PropertyID::BorderLeftColor:
- return resolve_color_style_value(*get_computed_value(property_id), layout_node.border_left().color, color_resolution_style);
- case PropertyID::BorderRightColor:
- return resolve_color_style_value(*get_computed_value(property_id), layout_node.border_right().color, color_resolution_style);
- case PropertyID::BorderTopColor:
- return resolve_color_style_value(*get_computed_value(property_id), layout_node.border_top().color, color_resolution_style);
- case PropertyID::BoxShadow:
- return style_value_for_shadow(ShadowStyleValue::ShadowType::Normal, layout_node.box_shadow(), layout_node.color());
- case PropertyID::CaretColor:
- return resolve_color_style_value(*get_computed_value(property_id), layout_node.caret_color(), color_resolution_style);
- case PropertyID::Color: {
- auto style = element.computed_style(pseudo_element);
+ auto abstract_element = *owner_node();
+ auto const* element_style = abstract_element.element().style_record_groups(abstract_element.pseudo_element());
+ VERIFY(element_style);
+ auto computed_value = [](void* context, u16 computed_property_id) -> StyleValueFFI::StyleValueData const* {
+ auto style = static_cast<DOM::AbstractElement*>(context)->computed_style();
VERIFY(style);
- return resolve_color_style_value(*get_computed_value(property_id), style->color(), ColorResolutionStyle::for_element(*owner_node()));
- }
- case PropertyID::Fill:
- case PropertyID::FloodColor:
- case PropertyID::StopColor:
- case PropertyID::Stroke:
- return resolve_svg_color_style_value(*get_computed_value(property_id), color_resolution_style);
- case PropertyID::ColumnRuleColor:
- return resolve_color_style_value(*get_computed_value(property_id), layout_node.column_rule_color(), color_resolution_style);
- case PropertyID::OutlineColor:
- return resolve_color_style_value(*get_computed_value(property_id), layout_node.outline_color(), color_resolution_style);
- case PropertyID::TextDecorationColor:
- return resolve_color_style_value(*get_computed_value(property_id), layout_node.text_decoration_color(), color_resolution_style);
- case PropertyID::TextShadow:
- return style_value_for_shadow(ShadowStyleValue::ShadowType::Text, layout_node.text_shadow(), layout_node.color());
- case PropertyID::BackdropFilter:
- case PropertyID::Filter:
- return resolve_filter_style_value(*get_computed_value(property_id), layout_node.color());
- case PropertyID::TouchAction:
- return resolve_touch_action_style_value(get_computed_value(property_id));
-
- // -> line-height
- // The resolved value is normal if the computed value is normal, or the used value otherwise.
- case PropertyID::LineHeight: {
- auto line_height = get_computed_value(property_id);
- if (line_height->is_keyword() && line_height->to_keyword() == Keyword::Normal)
- return line_height;
- auto const* font_values = element.style_group<ComputedValues::FontValues>(pseudo_element);
- VERIFY(font_values);
- return LengthStyleValue::create(Length::make_px(font_values->line_height_used_value()));
- }
-
- // -> block-size
- // -> height
- // -> inline-size
- // -> margin-block-end
- // -> margin-block-start
- // -> margin-bottom
- // -> margin-inline-end
- // -> margin-inline-start
- // -> margin-left
- // -> margin-right
- // -> margin-top
- // -> padding-block-end
- // -> padding-block-start
- // -> padding-bottom
- // -> padding-inline-end
- // -> padding-inline-start
- // -> padding-left
- // -> padding-right
- // -> padding-top
- // -> width
- // If the property applies to the element or pseudo-element and the resolved value of the
- // display property is not none or contents, then the resolved value is the used value.
- // Otherwise the resolved value is the computed value.
- case PropertyID::Height: {
- if (!svg_sizing_properties_apply(element))
- return get_computed_value(property_id);
- auto maybe_used_height = used_size_for_property(
- [](auto const& box_layout_node) { return Painting::content_height(box_layout_node); },
- [](auto const& box_layout_node) { return Painting::unbroken_border_box_size(box_layout_node).height(); });
- if (maybe_used_height.has_value())
- return LengthStyleValue::create(Length::make_px(maybe_used_height.release_value()));
- return get_computed_value(property_id);
- }
- case PropertyID::MarginBottom:
- return resolved_value_for_margin(principal_layout_node.margin().bottom(), [](auto const& box_layout_node) { return Painting::box_model(box_layout_node).margin.bottom; });
- case PropertyID::MarginLeft:
- return resolved_value_for_margin(principal_layout_node.margin().left(), [](auto const& box_layout_node) { return Painting::box_model(box_layout_node).margin.left; });
- case PropertyID::MarginRight:
- return resolved_value_for_margin(principal_layout_node.margin().right(), [](auto const& box_layout_node) { return Painting::box_model(box_layout_node).margin.right; });
- case PropertyID::MarginTop:
- return resolved_value_for_margin(principal_layout_node.margin().top(), [](auto const& box_layout_node) { return Painting::box_model(box_layout_node).margin.top; });
- case PropertyID::PaddingBottom:
- if (auto maybe_used_value = used_value_for_property([](auto const& box_layout_node) { return Painting::box_model(box_layout_node).padding.bottom; }); maybe_used_value.has_value())
- return LengthStyleValue::create(Length::make_px(maybe_used_value.release_value()));
- return style_value_for_length_percentage_or_auto(layout_node.padding().bottom());
- case PropertyID::PaddingLeft:
- if (auto maybe_used_value = used_value_for_property([](auto const& box_layout_node) { return Painting::box_model(box_layout_node).padding.left; }); maybe_used_value.has_value())
- return LengthStyleValue::create(Length::make_px(maybe_used_value.release_value()));
- return style_value_for_length_percentage_or_auto(layout_node.padding().left());
- case PropertyID::PaddingRight:
- if (auto maybe_used_value = used_value_for_property([](auto const& box_layout_node) { return Painting::box_model(box_layout_node).padding.right; }); maybe_used_value.has_value())
- return LengthStyleValue::create(Length::make_px(maybe_used_value.release_value()));
- return style_value_for_length_percentage_or_auto(layout_node.padding().right());
- case PropertyID::PaddingTop:
- if (auto maybe_used_value = used_value_for_property([](auto const& box_layout_node) { return Painting::box_model(box_layout_node).padding.top; }); maybe_used_value.has_value())
- return LengthStyleValue::create(Length::make_px(maybe_used_value.release_value()));
- return style_value_for_length_percentage_or_auto(layout_node.padding().top());
- case PropertyID::Width: {
- if (!svg_sizing_properties_apply(element))
- return get_computed_value(property_id);
- auto maybe_used_width = used_size_for_property(
- [](auto const& box_layout_node) { return Painting::content_width(box_layout_node); },
- [](auto const& box_layout_node) { return Painting::unbroken_border_box_size(box_layout_node).width(); });
- if (maybe_used_width.has_value())
- return LengthStyleValue::create(Length::make_px(maybe_used_width.release_value()));
- return get_computed_value(property_id);
- }
-
- // NB: The computed value of a min or max sizing property resolves its anchor-size() functions, which layout
- // resolves against an anchor box.
- case PropertyID::MaxHeight:
- case PropertyID::MaxWidth:
- case PropertyID::MinHeight:
- case PropertyID::MinWidth:
- if (auto resolved_size = Painting::anchor_resolved_size(layout_node, property_id); resolved_size.has_value())
- return LengthStyleValue::create(Length::make_px(resolved_size.release_value()));
- return resolve_unresolvable_anchor_functions(property_id, get_computed_value(property_id));
-
- // -> bottom
- // -> left
- // -> inset-block-end
- // -> inset-block-start
- // -> inset-inline-end
- // -> inset-inline-start
- // -> right
- // -> top
- // -> A resolved value special case property like top defined in another specification
- // If the property applies to a positioned element and the resolved value of the display property is not
- // none or contents, and the property is not over-constrained, then the resolved value is the used value.
- // Otherwise the resolved value is the computed value.
- case PropertyID::Bottom: {
- auto inset = principal_layout_node.inset();
- return resolved_value_for_inset(inset.bottom(), inset.top(), InsetAxis::Vertical, [](auto const& box_layout_node) { return Painting::box_model(box_layout_node).inset.bottom; });
- }
- case PropertyID::Left: {
- auto inset = principal_layout_node.inset();
- return resolved_value_for_inset(inset.left(), inset.right(), InsetAxis::Horizontal, [](auto const& box_layout_node) { return Painting::box_model(box_layout_node).inset.left; });
- }
- case PropertyID::Right: {
- auto inset = principal_layout_node.inset();
- return resolved_value_for_inset(inset.right(), inset.left(), InsetAxis::Horizontal, [](auto const& box_layout_node) { return Painting::box_model(box_layout_node).inset.right; });
- }
- case PropertyID::Top: {
- auto inset = principal_layout_node.inset();
- return resolved_value_for_inset(inset.top(), inset.bottom(), InsetAxis::Vertical, [](auto const& box_layout_node) { return Painting::box_model(box_layout_node).inset.top; });
- }
-
- // -> A resolved value special case property defined in another specification
- // As defined in the relevant specification.
- case PropertyID::Transform: {
- if (!layout_node.has_transformations())
- return KeywordStyleValue::create(Keyword::None);
-
- // https://drafts.csswg.org/css-transforms-2/#serialization-of-the-computed-value
- // The transform property is a resolved value special case property. [CSSOM]
- // When the computed value is a <transform-list>, the resolved value is one <matrix()> function or one <matrix3d()> function computed by the following algorithm:
- // 1. Let transform be a 4x4 matrix initialized to the identity matrix.
- // The elements m11, m22, m33 and m44 of transform must be set to 1; all other elements of transform must be set to 0.
- auto transform = FloatMatrix4x4::identity();
-
- // 2. Post-multiply all <transform-function>s in <transform-list> to transform.
- // NB: The resolved transforms start with those of the translate, rotate and scale properties.
- VERIFY(Painting::has_committed_box(layout_node));
- auto reference_box = Painting::transform_reference_box(layout_node);
- size_t individual_transform_count = layout_node.has_translate() + layout_node.has_rotate() + layout_node.has_scale();
- size_t index = 0;
- layout_node.for_each_resolved_transform([&](auto const& resolved_transform) {
- if (index++ >= individual_transform_count)
- transform = transform * resolved_transform.to_matrix(reference_box.width(), reference_box.height());
- });
-
- // https://drafts.csswg.org/css-transforms-1/#2d-matrix
- auto is_2d_matrix = [](Gfx::FloatMatrix4x4 const& matrix) -> bool {
- // A 3x2 transformation matrix,
- // or a 4x4 matrix where the items m31, m32, m13, m23, m43, m14, m24, m34 are equal to 0
- // and m33, m44 are equal to 1.
- // NB: We only care about 4x4 matrices here.
- // NB: Our elements are 0-indexed not 1-indexed, and in the opposite order.
- // NB: We use epsilon comparisons here to account for inaccuracies when doing trigonometric calculations.
- if (abs(matrix[0, 2]) > AK::NumericLimits<float>::epsilon() // m31
- || abs(matrix[1, 2]) > AK::NumericLimits<float>::epsilon() // m32
- || abs(matrix[2, 0]) > AK::NumericLimits<float>::epsilon() // m13
- || abs(matrix[2, 1]) > AK::NumericLimits<float>::epsilon() // m23
- || abs(matrix[2, 3]) > AK::NumericLimits<float>::epsilon() // m43
- || abs(matrix[3, 0]) > AK::NumericLimits<float>::epsilon() // m14
- || abs(matrix[3, 1]) > AK::NumericLimits<float>::epsilon() // m24
- || abs(matrix[3, 2]) > AK::NumericLimits<float>::epsilon()) // m34
- return false;
-
- if (abs(matrix[2, 2]) - 1 > AK::NumericLimits<float>::epsilon() // m33
- || abs(matrix[3, 3]) - 1 > AK::NumericLimits<float>::epsilon()) // m44
- return false;
-
- return true;
- };
-
- // 3. Chose between <matrix()> or <matrix3d()> serialization:
- // -> If transform is a 2D matrix
- // Serialize transform to a <matrix()> function.
- if (is_2d_matrix(transform)) {
- StyleValueVector parameters {
- NumberStyleValue::create(transform[0, 0]),
- NumberStyleValue::create(transform[1, 0]),
- NumberStyleValue::create(transform[0, 1]),
- NumberStyleValue::create(transform[1, 1]),
- NumberStyleValue::create(transform[0, 3]),
- NumberStyleValue::create(transform[1, 3]),
- };
- return TransformationStyleValue::create(PropertyID::Transform, TransformFunction::Matrix, move(parameters));
- }
- // -> Otherwise
- // Serialize transform to a <matrix3d()> function.
- else {
- StyleValueVector parameters {
- NumberStyleValue::create(transform[0, 0]),
- NumberStyleValue::create(transform[1, 0]),
- NumberStyleValue::create(transform[2, 0]),
- NumberStyleValue::create(transform[3, 0]),
- NumberStyleValue::create(transform[0, 1]),
- NumberStyleValue::create(transform[1, 1]),
- NumberStyleValue::create(transform[2, 1]),
- NumberStyleValue::create(transform[3, 1]),
- NumberStyleValue::create(transform[0, 2]),
- NumberStyleValue::create(transform[1, 2]),
- NumberStyleValue::create(transform[2, 2]),
- NumberStyleValue::create(transform[3, 2]),
- NumberStyleValue::create(transform[0, 3]),
- NumberStyleValue::create(transform[1, 3]),
- NumberStyleValue::create(transform[2, 3]),
- NumberStyleValue::create(transform[3, 3]),
- };
- return TransformationStyleValue::create(PropertyID::Transform, TransformFunction::Matrix3d, move(parameters));
- }
- }
- case PropertyID::TransformOrigin: {
- // https://drafts.csswg.org/css-transforms/#transform-origin-property
- // The transform-origin property is a resolved value special case property like height. [CSSOM]
- Optional<CSSPixelRect> reference_box;
- if (auto display = layout_node.display(); !display.is_none() && !display.is_contents()) {
- if (Painting::has_committed_box(layout_node))
- reference_box = Painting::transform_reference_box(layout_node);
- }
- return style_value_for_transform_origin(layout_node.transform_origin(), reference_box);
- }
- case PropertyID::PerspectiveOrigin: {
- // https://drafts.csswg.org/css-transforms-2/#perspective-origin-property
- // The perspective-origin property is a resolved value special case property like height. [CSSOM]
- Optional<CSSPixelRect> reference_box;
- if (auto display = layout_node.display(); !display.is_none() && !display.is_contents()) {
- if (Painting::has_committed_box(layout_node))
- reference_box = Painting::transform_reference_box(layout_node);
- }
- if (!reference_box.has_value())
- return get_computed_value(property_id);
- auto const& transform_values = layout_node.style_group<ComputedValues::TransformValues>();
- TransformOrigin perspective_origin {
- LengthPercentage::view(transform_values.perspective_origin_x),
- LengthPercentage::view(transform_values.perspective_origin_y),
- Length::make_px(0),
- };
- return style_value_for_transform_origin(perspective_origin, reference_box);
- }
- case PropertyID::AnimationDuration: {
- // https://drafts.csswg.org/css-animations-2/#animation-duration
- // For backwards-compatibility with Level 1, when the computed value of animation-timeline is auto (i.e. only
- // one list value, and that value being auto), the resolved value of auto for animation-duration is 0s whenever
- // its used value would also be 0s.
- auto animation_timeline_computed_value = get_computed_value(PropertyID::AnimationTimeline);
- auto animation_duration_computed_value = get_computed_value(PropertyID::AnimationDuration);
-
- if (animation_timeline_computed_value->as_value_list().size() == 1 && animation_timeline_computed_value->as_value_list().values()[0]->to_keyword() == Keyword::Auto) {
- StyleValueVector resolved_durations;
-
- for (auto const& duration : animation_duration_computed_value->as_value_list().values()) {
- if (duration->to_keyword() == Keyword::Auto) {
- resolved_durations.append(TimeStyleValue::create(Time::make_seconds(0)));
- } else {
- resolved_durations.append(duration);
- }
- }
-
- return StyleValueList::create(move(resolved_durations), StyleValueList::Separator::Comma);
- }
-
- return animation_duration_computed_value;
- }
- // If the border-style corresponding to a given border-width is none or hidden, then the used width is 0.
- // https://drafts.csswg.org/css-backgrounds/#border-width
- // NB: We do this adjustment when assigning to ComputedValues, so read from there.
- case PropertyID::BorderBottomWidth:
- return LengthStyleValue::create(Length::make_px(layout_node.border_bottom().width));
- case PropertyID::BorderLeftWidth:
- return LengthStyleValue::create(Length::make_px(layout_node.border_left().width));
- case PropertyID::BorderRightWidth:
- return LengthStyleValue::create(Length::make_px(layout_node.border_right().width));
- case PropertyID::BorderTopWidth:
- return LengthStyleValue::create(Length::make_px(layout_node.border_top().width));
-
- // -> Any other property
- // The resolved value is the computed value.
- case PropertyID::WebkitTextFillColor:
- return resolve_color_style_value(*get_computed_value(property_id), layout_node.webkit_text_fill_color(), color_resolution_style);
- case PropertyID::LetterSpacing: {
- // https://drafts.csswg.org/css-text-4/#letter-spacing-property
- // For legacy reasons, a computed letter-spacing of zero yields a resolved value (getComputedStyle() return value) of normal.
- if (layout_node.letter_spacing() == 0)
- return KeywordStyleValue::create(Keyword::Normal);
- return get_computed_value(property_id);
- }
- case PropertyID::Custom:
- dbgln_if(LIBWEB_CSS_DEBUG, "Computed style for custom properties was requested (?)");
- return nullptr;
- default:
- // For grid-template-columns and grid-template-rows the resolved value is the used value.
- // https://www.w3.org/TR/css-grid-2/#resolved-track-list-standalone
- if ((property_id == PropertyID::GridTemplateColumns || property_id == PropertyID::GridTemplateRows) && Painting::has_committed_box(layout_node)) {
- if (auto value = Painting::used_value_for_grid_template(layout_node, property_id))
- return StyleValue::adopt_rust_style_value_data(value.leak_data());
- }
-
- if (!property_is_shorthand(property_id)) {
- return get_computed_value(property_id);
- }
-
- // Handle shorthands in a generic way
- auto longhand_ids = longhands_for_shorthand(property_id);
- StyleValueVector longhand_values;
- longhand_values.ensure_capacity(longhand_ids.size());
- for (auto longhand_id : longhand_ids)
- longhand_values.append(style_value_for_computed_property(layout_node, longhand_id).release_nonnull());
- return ShorthandStyleValue::create(property_id, move(longhand_ids), move(longhand_values));
- }
+ auto value = style->computed_style_value(static_cast<PropertyID>(computed_property_id));
+ VERIFY(value);
+ return StyleValueFFI::rust_style_value_retain(value->rust_style_value_data());
+ };
+ StyleValueFFI::FfiResolvedValueBox resolved_value_box {
+ .host = layout_node.document_host(),
+ .node = Layout::Node::slot_id(&layout_node).index,
+ .principal_node = Layout::Node::slot_id(&principal_layout_node).index,
+ .has_containing_block = containing_block != nullptr,
+ .containing_block = containing_block ? Layout::Node::slot_id(containing_block).index : 0,
+ .has_scroll_container = scroll_container != nullptr,
+ .scroll_container = scroll_container ? Layout::Node::slot_id(scroll_container).index : 0,
+ .element_style = element_style,
+ .svg_sizing_properties_apply = svg_sizing_properties_apply(abstract_element.element()),
+ .computed_value_context = &abstract_element,
+ .computed_value = computed_value,
+ };
+ return StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_resolved_value_of_box(&resolved_value_box, to_underlying(property_id)));
}
// https://drafts.csswg.org/cssom/#dom-cssstyledeclaration-removeproperty
diff --git a/Libraries/LibWeb/Rust/src/css/resolved_value.rs b/Libraries/LibWeb/Rust/src/css/resolved_value.rs
index cef659323d3..9f0a05121ef 100644
--- a/Libraries/LibWeb/Rust/src/css/resolved_value.rs
+++ b/Libraries/LibWeb/Rust/src/css/resolved_value.rs
@@ -7,25 +7,43 @@
//! The resolved values of the properties whose resolved value is not their computed value.
//! https://drafts.csswg.org/cssom/#resolved-values
+use core::ffi::c_void;
+
+use crate::css::calc::canonical_unit_code;
use crate::css::color_conversion::{LAB, LCH, OKLAB, OKLCH};
use crate::css::color_resolution::{
ColorResolutionInput, FfiColorResolutionStyle, Rgba, SerializationBehavior, descriptor_for_color_type,
resolve_color_mix, resolve_relative_form, to_color,
};
-use crate::css::computed_value_types::ComputedShadow;
-use crate::css::css_enums::keyword;
-use crate::css::css_pixels::CssPixels;
+use crate::css::computed_value_types::{ComputedLengthPercentageOrAuto, ComputedShadow, ComputedStyleValueHandle};
+use crate::css::computed_value_views::{ComputedValuesView, StyleRecordGroups, resolve_calc_to_px_without_rounding};
+use crate::css::css_enums::{box_sizing, keyword, positioning, writing_mode};
+use crate::css::css_pixels::{
+ CssPixelRect, CssPixels, FfiCssPixelRect, FfiCssPixelSize, MAX_INTEGER_VALUE, MIN_INTEGER_VALUE,
+};
+use crate::css::property_metadata::{
+ longhand_is_logical_alias, longhands_for_shorthand, property_id, property_is_shorthand,
+};
use crate::css::serialize::color_function_has_missing_component;
+use crate::css::serialize::transform_function;
+use crate::css::style_compute::map_logical_alias_to_physical;
use crate::css::style_value::{
- ColorBase, ColorFunctionPayload, CssString, FILTER_KIND_DROP_SHADOW, RetainedStyleValueData,
- RetainedStyleValueDataList, ShadowPayload, StyleValueBox, StyleValueData, shared_style_value,
- value_depends_on_current_color,
+ ColorBase, ColorFunctionPayload, CssString, FILTER_KIND_DROP_SHADOW, RetainedPropertyIdList,
+ RetainedStyleValueData, RetainedStyleValueDataList, ShadowPayload, ShorthandPayload, StyleValueBox, StyleValueData,
+ TransformationPayload, shared_style_value, value_depends_on_current_color,
};
use crate::css::style_value_arc::StyleValueArc;
use crate::css::value_codes::{COLOR_SYNTAX_MODERN, COLOR_TYPE_RGB};
+use crate::layout::node_data::NodeSlotId;
+use crate::layout::script_entries::FfiAnchorSizedProperty;
+use crate::painting::ffi::FfiBoxModelMetrics;
+use crate::painting::visual_context::node_values::multiply_transform_functions;
+use crate::render_state::DocumentHost;
const VALUE_LIST_SEPARATOR_SPACE: u8 = 0;
const VALUE_LIST_SEPARATOR_COMMA: u8 = 1;
+const SHADOW_TYPE_NORMAL: u8 = 0;
+const SHADOW_TYPE_TEXT: u8 = 1;
fn number(value: f64) -> RetainedStyleValueData {
RetainedStyleValueData::from_arc(shared_style_value(StyleValueData::Number { value }))
@@ -34,7 +52,7 @@ fn number(value: f64) -> RetainedStyleValueData {
fn length_px(value: f64) -> RetainedStyleValueData {
RetainedStyleValueData::from_arc(shared_style_value(StyleValueData::Length {
value,
- unit: crate::css::calc::canonical_unit_code(&crate::css::style_compute::LENGTH_UNIT_CANONICAL_PX_RATIOS),
+ unit: canonical_unit_code(&crate::css::style_compute::LENGTH_UNIT_CANONICAL_PX_RATIOS),
}))
}
@@ -328,3 +346,755 @@ pub unsafe extern "C" fn rust_resolved_shadow_value(
Rgba::from_packed(current_color),
))
}
+
+const TIME_UNIT_SECONDS: u8 = 1;
+
+fn length_value(pixels: f64) -> StyleValueArc {
+ length_px(pixels).into_arc()
+}
+
+fn keyword_value(keyword: u16) -> StyleValueArc {
+ shared_style_value(StyleValueData::Keyword { keyword })
+}
+
+fn absolute_length_px(value: &StyleValueData) -> Option<f64> {
+ match value {
+ StyleValueData::Length { value, unit } => crate::css::style_compute::absolute_length_to_px(*value, *unit),
+ _ => None,
+ }
+}
+
+fn handle_value(handle: &ComputedStyleValueHandle) -> Option<&StyleValueData> {
+ // SAFETY: A non-null handle points at the style value the group payload retains.
+ unsafe { handle.pointer.cast::<StyleValueData>().as_ref() }
+}
+
+fn style_value_for_length_percentage(value: &StyleValueData) -> StyleValueArc {
+ retained(value)
+}
+
+fn style_value_for_length_percentage_or_auto(value: &ComputedLengthPercentageOrAuto) -> StyleValueArc {
+ if value.is_auto {
+ return keyword_value(keyword::AUTO);
+ }
+ retained(handle_value(&value.value).expect("a computed length-percentage holds a value"))
+}
+
+/// The value of a length-percentage against `reference`, in pixels and without rounding.
+fn offset_in_px(offset: &StyleValueData, reference: CssPixels) -> f64 {
+ match offset {
+ StyleValueData::Percentage { value } => reference.to_double() * (value * 0.01),
+ StyleValueData::Calculated(_) => {
+ resolve_calc_to_px_without_rounding(std::ptr::from_ref(offset).cast(), reference)
+ }
+ value => absolute_length_px(value).expect("a computed length-percentage is absolute"),
+ }
+}
+
+fn style_value_for_transform_origin(
+ x: &StyleValueData,
+ y: &StyleValueData,
+ z: Option<&StyleValueData>,
+ reference_box: Option<CssPixelRect>,
+) -> StyleValueArc {
+ let mut offsets = match reference_box {
+ Some(reference_box) => vec![
+ length_px(offset_in_px(x, reference_box.width)),
+ length_px(offset_in_px(y, reference_box.height)),
+ ],
+ None => vec![
+ RetainedStyleValueData::from_arc(style_value_for_length_percentage(x)),
+ RetainedStyleValueData::from_arc(style_value_for_length_percentage(y)),
+ ],
+ };
+ if let Some(z) = z {
+ let z_offset = offset_in_px(z, CssPixels::from_raw(0));
+ if z_offset != 0.0 {
+ offsets.push(length_px(z_offset));
+ }
+ }
+ StyleValueArc::new(StyleValueData::ValueList {
+ values: RetainedStyleValueDataList::from_retained_values(offsets),
+ separator: VALUE_LIST_SEPARATOR_SPACE,
+ collapsible: false,
+ })
+}
+
+// NB: The computed value of a min or max sizing property resolves its anchor-size() functions. Where layout did not
+// resolve them against an anchor box, they are unresolvable: each resolves to its fallback value, and one without
+// makes the declaration invalid at computed-value time.
+fn resolve_unresolvable_anchor_functions(property: u16, computed_value: StyleValueArc) -> StyleValueArc {
+ let mut is_invalid = false;
+ let substituted =
+ crate::css::calc::rust_style_value_with_unresolvable_anchor_functions(&computed_value, &mut is_invalid);
+ if !substituted.is_null() {
+ // SAFETY: The call hands over one strong reference.
+ return unsafe { StyleValueArc::from_raw(substituted) };
+ }
+ if is_invalid {
+ return retained(crate::css::style_compute::initial_value(property).expect("a longhand has an initial value"));
+ }
+ computed_value
+}
+
+// https://drafts.csswg.org/css-transforms-1/#2d-matrix
+fn is_2d_matrix(matrix: &libgfx_rust::FloatMatrix4x4) -> bool {
+ // A 3x2 transformation matrix,
+ // or a 4x4 matrix where the items m31, m32, m13, m23, m43, m14, m24, m34 are equal to 0
+ // and m33, m44 are equal to 1.
+ // NB: We only care about 4x4 matrices here.
+ // NB: Our elements are 0-indexed not 1-indexed, and in the opposite order.
+ // NB: We use epsilon comparisons here to account for inaccuracies when doing trigonometric calculations.
+ let m = &matrix.elements;
+ [m[0][2], m[1][2], m[2][0], m[2][1], m[2][3], m[3][0], m[3][1], m[3][2]]
+ .iter()
+ .all(|element| element.abs() <= f32::EPSILON)
+ && m[2][2].abs() - 1.0 <= f32::EPSILON
+ && m[3][3].abs() - 1.0 <= f32::EPSILON
+}
+
+fn transformation_value(transform_function: u8, parameters: &[f32]) -> StyleValueArc {
+ StyleValueArc::new(StyleValueData::Transformation(StyleValueBox::new(
+ TransformationPayload {
+ property: property_id::TRANSFORM,
+ transform_function,
+ values: RetainedStyleValueDataList::from_retained_values(
+ parameters
+ .iter()
+ .map(|&parameter| number(f64::from(parameter)))
+ .collect(),
+ ),
+ matrix_values: RetainedStyleValueDataList::from_retained_values(Vec::new()),
+ },
+ )))
+}
+
+/// What the host names for the box of the element whose resolved value is read.
+#[repr(C)]
+pub struct FfiResolvedValueBox {
+ pub host: *const c_void,
+ /// The element's layout node.
+ pub node: u32,
+ /// The layout node holding its insets and margins: its table wrapper for a table.
+ pub principal_node: u32,
+ pub has_containing_block: bool,
+ /// The containing block of the principal node.
+ pub containing_block: u32,
+ pub has_scroll_container: bool,
+ /// The nearest scroll container of the principal node, for sticky positioning.
+ pub scroll_container: u32,
+ /// The groups of the style of the element, or pseudo-element, itself.
+ pub element_style: *const c_void,
+ pub svg_sizing_properties_apply: bool,
+ pub computed_value_context: *mut c_void,
+ /// The computed value of a longhand of the element, as one strong reference.
+ pub computed_value: unsafe extern "C" fn(context: *mut c_void, property: u16) -> *const StyleValueData,
+}
+
+struct ResolvedValueBox<'a> {
+ query: &'a FfiResolvedValueBox,
+ host: &'a DocumentHost,
+ node: NodeSlotId,
+ principal_node: NodeSlotId,
+ style: ComputedValuesView<'a>,
+ principal_style: ComputedValuesView<'a>,
+ element_style: ComputedValuesView<'a>,
+}
+
+fn node_style(host: &DocumentHost, node: NodeSlotId) -> ComputedValuesView<'_> {
+ let groups = crate::layout::shell_reads::layout_row_style(host, node);
+ assert!(!groups.is_null(), "a layout node has a style");
+ // SAFETY: The style of a layout node stays live while the host reads the node.
+ ComputedValuesView::of_record_groups(unsafe { &*groups.cast::<StyleRecordGroups>() })
+}
+
+fn has_committed_box(host: &DocumentHost, node: NodeSlotId) -> bool {
+ crate::painting::ffi::render_state_has_paintable_row(host, node)
+}
+
+fn box_model(host: &DocumentHost, node: NodeSlotId) -> FfiBoxModelMetrics {
+ let mut metrics = FfiBoxModelMetrics::default();
+ crate::layout::script_entries::layout_script_paintable_box_model(host, node, &mut metrics);
+ metrics
+}
+
+fn content_size(host: &DocumentHost, node: NodeSlotId) -> FfiCssPixelSize {
+ let mut size = FfiCssPixelSize::default();
+ crate::layout::script_entries::layout_script_paintable_content_size(host, node, &mut size);
+ size
+}
+
+fn transform_reference_box(host: &DocumentHost, node: NodeSlotId) -> CssPixelRect {
+ let mut rect = FfiCssPixelRect::default();
+ crate::painting::ffi::render_state_paintable_transform_reference_box(host, node, &mut rect);
+ rect.into()
+}
+
+#[derive(Clone, Copy)]
+enum InsetAxis {
+ Horizontal,
+ Vertical,
+}
+
+impl ResolvedValueBox<'_> {
+ fn computed(&self, property: u16) -> StyleValueArc {
+ // SAFETY: The host passes a live context, and the call hands over one strong reference.
+ unsafe { StyleValueArc::from_raw((self.query.computed_value)(self.query.computed_value_context, property)) }
+ }
+
+ fn containing_block(&self) -> Option<NodeSlotId> {
+ self.query.has_containing_block.then_some(NodeSlotId {
+ index: self.query.containing_block,
+ })
+ }
+
+ fn has_used_box(&self, node: NodeSlotId, style: ComputedValuesView) -> bool {
+ let display = style.display();
+ !display.is_none() && !display.is_contents() && has_committed_box(self.host, node)
+ }
+
+ fn resolved_color(&self, property: u16, used_color: u32) -> StyleValueArc {
+ resolve_color_style_value(
+ &self.computed(property),
+ Rgba::from_packed(used_color),
+ Some(&ColorResolutionInput::for_style(self.style)),
+ )
+ }
+
+ // https://drafts.csswg.org/cssom/#resolved-value-special-case-property-like-height
+ // If the property applies to the element or pseudo-element and the resolved value of the display property is not
+ // none or contents, then the resolved value is the used value. Otherwise the resolved value is the computed value.
+ fn resolved_value_for_margin(
+ &self,
+ margin: &ComputedLengthPercentageOrAuto,
+ used_value: impl FnOnce(&FfiBoxModelMetrics) -> CssPixels,
+ ) -> StyleValueArc {
+ if !self.has_used_box(self.principal_node, self.principal_style) {
+ return style_value_for_length_percentage_or_auto(margin);
+ }
+ let used_value = used_value(&box_model(self.host, self.principal_node)).to_double();
+ let containing_block = self.containing_block();
+ let containing_block_style = containing_block.map(|node| node_style(self.host, node));
+ // NB: Positioned boxes can have position-try overrides, and grid/flex items can use a specialized basis.
+ let is_absolutely_positioned = matches!(
+ self.principal_style.position(),
+ positioning::ABSOLUTE | positioning::FIXED
+ );
+ if !self.principal_style.display().is_block_outside()
+ || is_absolutely_positioned
+ || containing_block_style.is_some_and(|style| {
+ let display = style.display();
+ display.is_grid_inside() || display.is_flex_inside()
+ })
+ {
+ return length_value(used_value);
+ }
+ let resolved_length = |pixels: f64| {
+ // NB: Retain fractional precision within the layout range, and preserve saturation outside it.
+ if pixels < f64::from(MIN_INTEGER_VALUE) || pixels > f64::from(MAX_INTEGER_VALUE) {
+ return length_value(CssPixels::nearest_value_for(pixels).to_double());
+ }
+ length_value(pixels)
+ };
+ // INTEROP: Chrome and Safari exclude the adjustment that satisfies an over-constrained block's inline-size
+ // equation.
+ let value = handle_value(&margin.value);
+ if let Some(pixels) = value.filter(|_| !margin.is_auto).and_then(absolute_length_px) {
+ return resolved_length(pixels);
+ }
+ if !margin.is_auto
+ && let (Some(node), Some(style), Some(value)) = (containing_block, containing_block_style, value)
+ && has_committed_box(self.host, node)
+ {
+ let size = content_size(self.host, node);
+ let basis = if style.writing_mode() == writing_mode::HORIZONTAL_TB {
+ size.width
+ } else {
+ size.height
+ };
+ return match value {
+ StyleValueData::Percentage { value } => resolved_length(basis.to_double() * (value * 0.01)),
+ value => match crate::css::calc::resolve_calculated_length_without_context(value, basis.to_double()) {
+ Some(pixels) => resolved_length(pixels),
+ None => length_value(used_value),
+ },
+ };
+ }
+ length_value(used_value)
+ }
+
+ fn resolved_value_for_padding(
+ &self,
+ padding: &ComputedLengthPercentageOrAuto,
+ used_value: impl FnOnce(&FfiBoxModelMetrics) -> CssPixels,
+ ) -> StyleValueArc {
+ if self.has_used_box(self.node, self.style) {
+ return length_value(used_value(&box_model(self.host, self.node)).to_double());
+ }
+ style_value_for_length_percentage_or_auto(padding)
+ }
+
+ fn resolved_value_for_size(
+ &self,
+ property: u16,
+ content_box: impl FnOnce(FfiCssPixelSize) -> CssPixels,
+ border_box: impl FnOnce(FfiCssPixelSize) -> CssPixels,
+ ) -> StyleValueArc {
+ if !self.query.svg_sizing_properties_apply || !self.has_used_box(self.node, self.style) {
+ return self.computed(property);
+ }
+ let used_value = if self.style.box_sizing() == box_sizing::BORDER_BOX {
+ let mut size = FfiCssPixelSize::default();
+ crate::layout::script_entries::layout_script_paintable_unbroken_border_box_size(
+ self.host, self.node, &mut size,
+ );
+ border_box(size)
+ } else {
+ content_box(content_size(self.host, self.node))
+ };
+ length_value(used_value.to_double())
+ }
+
+ // https://drafts.csswg.org/cssom/#resolved-value-special-case-property-like-top
+ fn resolved_value_for_inset(
+ &self,
+ side: &ComputedLengthPercentageOrAuto,
+ opposite_side: &ComputedLengthPercentageOrAuto,
+ axis: InsetAxis,
+ used_value: impl FnOnce(&FfiBoxModelMetrics) -> CssPixels,
+ ) -> StyleValueArc {
+ let computed_value = || style_value_for_length_percentage_or_auto(side);
+ let position = self.principal_style.position();
+ if position == positioning::STATIC || !self.has_used_box(self.principal_node, self.principal_style) {
+ return computed_value();
+ }
+
+ // NB: The used value of a fixed length is the length itself. Taking it from the computed value keeps
+ // the precision that layout units would lose. Layout saturates lengths beyond the range of layout
+ // units, so those are reported as saturated.
+ let value = handle_value(&side.value).filter(|_| !side.is_auto);
+ if let Some(pixels) = value.and_then(absolute_length_px) {
+ if pixels >= f64::from(MIN_INTEGER_VALUE) && pixels <= f64::from(MAX_INTEGER_VALUE) {
+ return computed_value();
+ }
+ return length_value(CssPixels::nearest_value_for(pixels).to_double());
+ }
+
+ let absolutized_against = |percentage_basis: CssPixels| {
+ length_value(offset_in_px(
+ value.expect("an inset to absolutize is not auto"),
+ percentage_basis,
+ ))
+ };
+ let size_in_axis = |size: FfiCssPixelSize| match axis {
+ InsetAxis::Horizontal => size.width,
+ InsetAxis::Vertical => size.height,
+ };
+
+ // https://drafts.csswg.org/css-position/#insets
+ // For sticky positioned boxes, the inset is instead relative to the relevant scrollport's size.
+ if position == positioning::STICKY {
+ // NB: Sticky positioning leaves an auto inset unconstrained, so its used value stays auto.
+ if side.is_auto {
+ return computed_value();
+ }
+ // NB: This uses the same scrollport size as the sticky constraints: the content box of the nearest
+ // scroll container, or of the viewport.
+ let scroll_container = NodeSlotId {
+ index: self.query.scroll_container,
+ };
+ if !self.query.has_scroll_container || !has_committed_box(self.host, scroll_container) {
+ return computed_value();
+ }
+ return absolutized_against(size_in_axis(content_size(self.host, scroll_container)));
+ }
+
+ // https://drafts.csswg.org/css-position/#relpos-insets
+ // If neither is auto, the position is over-constrained;
+ // NB: The resolved value is then the computed value, absolutized against the containing block.
+ // INTEROP: Percentages are absolutized rather than serialized as-is, to match other browsers.
+ if position == positioning::RELATIVE && !side.is_auto && !opposite_side.is_auto {
+ return match self
+ .containing_block()
+ .filter(|&node| has_committed_box(self.host, node))
+ {
+ Some(node) => absolutized_against(size_in_axis(content_size(self.host, node))),
+ None => computed_value(),
+ };
+ }
+
+ length_value(used_value(&box_model(self.host, self.principal_node)).to_double())
+ }
+
+ fn resolved_transform(&self) -> StyleValueArc {
+ let transform_values = self.style.transform();
+ if transform_values.transformations.pointer.is_null() {
+ return keyword_value(keyword::NONE);
+ }
+
+ // https://drafts.csswg.org/css-transforms-2/#serialization-of-the-computed-value
+ // The transform property is a resolved value special case property. [CSSOM]
+ // When the computed value is a <transform-list>, the resolved value is one <matrix()> function or one
+ // <matrix3d()> function computed by the following algorithm:
+ // 1. Let transform be a 4x4 matrix initialized to the identity matrix.
+ // The elements m11, m22, m33 and m44 of transform must be set to 1; all other elements of transform must be
+ // set to 0.
+ // 2. Post-multiply all <transform-function>s in <transform-list> to transform.
+ // NB: The resolved transforms start with those of the translate, rotate and scale properties.
+ assert!(has_committed_box(self.host, self.node));
+ let reference_box = transform_reference_box(self.host, self.node);
+ let individual_transform_count = [
+ &transform_values.translate,
+ &transform_values.rotate,
+ &transform_values.scale,
+ ]
+ .iter()
+ .filter(|handle| !handle.pointer.is_null())
+ .count();
+ let resolved_transforms = &transform_values.resolved_transforms;
+ // SAFETY: The list holds `length` transforms while the style lives.
+ let entries =
+ unsafe { ak::slice_from_raw_parts(resolved_transforms.pointer.cast_const(), resolved_transforms.length) };
+ let transform = multiply_transform_functions(
+ libgfx_rust::FloatMatrix4x4::identity(),
+ entries.get(individual_transform_count..).unwrap_or_default(),
+ reference_box,
+ );
+ let m = &transform.elements;
+
+ // 3. Chose between <matrix()> or <matrix3d()> serialization:
+ // -> If transform is a 2D matrix
+ // Serialize transform to a <matrix()> function.
+ if is_2d_matrix(&transform) {
+ return transformation_value(
+ transform_function::MATRIX,
+ &[m[0][0], m[1][0], m[0][1], m[1][1], m[0][3], m[1][3]],
+ );
+ }
+ // -> Otherwise
+ // Serialize transform to a <matrix3d()> function.
+ transformation_value(
+ transform_function::MATRIX3D,
+ &[
+ m[0][0], m[1][0], m[2][0], m[3][0], m[0][1], m[1][1], m[2][1], m[3][1], m[0][2], m[1][2], m[2][2],
+ m[3][2], m[0][3], m[1][3], m[2][3], m[3][3],
+ ],
+ )
+ }
+
+ fn reference_box_if_used(&self) -> Option<CssPixelRect> {
+ self.has_used_box(self.node, self.style)
+ .then(|| transform_reference_box(self.host, self.node))
+ }
+
+ fn resolved_animation_duration(&self) -> StyleValueArc {
+ // https://drafts.csswg.org/css-animations-2/#animation-duration
+ // For backwards-compatibility with Level 1, when the computed value of animation-timeline is auto (i.e. only
+ // one list value, and that value being auto), the resolved value of auto for animation-duration is 0s whenever
+ // its used value would also be 0s.
+ let is_auto = |value: &RetainedStyleValueData| matches!(value.optional_data(), Some(StyleValueData::Keyword { keyword }) if *keyword == keyword::AUTO);
+ let animation_timeline = self.computed(property_id::ANIMATION_TIMELINE);
+ let animation_duration = self.computed(property_id::ANIMATION_DURATION);
+ let (
+ StyleValueData::ValueList { values: timelines, .. },
+ StyleValueData::ValueList {
+ values: durations,
+ separator,
+ collapsible,
+ },
+ ) = (&*animation_timeline, &*animation_duration)
+ else {
+ unreachable!("the computed animation-timeline and animation-duration are lists");
+ };
+ if !matches!(timelines.as_slice(), [timeline] if is_auto(timeline)) {
+ return animation_duration.clone();
+ }
+ let resolved_durations = durations
+ .as_slice()
+ .iter()
+ .map(|duration| {
+ if !is_auto(duration) {
+ return duration.clone();
+ }
+ RetainedStyleValueData::from_arc(shared_style_value(StyleValueData::Time {
+ unit: TIME_UNIT_SECONDS,
+ value: 0.0,
+ }))
+ })
+ .collect();
+ StyleValueArc::new(StyleValueData::ValueList {
+ values: RetainedStyleValueDataList::from_retained_values(resolved_durations),
+ separator: *separator,
+ collapsible: *collapsible,
+ })
+ }
+
+ fn resolved_min_or_max_size(&self, property: u16, anchor_property: FfiAnchorSizedProperty) -> StyleValueArc {
+ let mut size = CssPixels::from_raw(0);
+ if crate::layout::script_entries::layout_script_anchor_resolved_size(
+ self.host,
+ self.node,
+ anchor_property,
+ &mut size,
+ ) {
+ return length_value(size.to_double());
+ }
+ resolve_unresolvable_anchor_functions(property, self.computed(property))
+ }
+
+ fn resolved_value(&self, property: u16) -> StyleValueArc {
+ let style = self.style;
+ let current_color = style.current_color();
+ let current = Rgba::from_packed(current_color);
+ let color_input = ColorResolutionInput::for_style(style);
+ let principal_surround = self.principal_style.surround();
+ let surround = style.surround();
+ let inset = &principal_surround.inset;
+
+ // A logical property maps by the element's own writing mode and direction, which its box may not show yet: a box
+ // awaiting the layout tree update that replaces it keeps the style it was built for.
+ // NB: A shorthand has no alias of its own to map.
+ let property = if !property_is_shorthand(property) && longhand_is_logical_alias(property) {
+ let element_style = self.element_style;
+ map_logical_alias_to_physical(property, element_style.writing_mode(), element_style.direction())
+ } else {
+ property
+ };
+
+ // A limited number of properties have special rules for producing their "resolved value".
+ // We also have to manually construct shorthands from their longhands here.
+ // Everything else uses the computed value.
+ // https://drafts.csswg.org/cssom/#resolved-values
+ match property {
+ property_id::BACKGROUND_COLOR => {
+ let element_style = self.element_style;
+ let value = handle_value(&element_style.background().background_color_style_value)
+ .expect("the background group holds a color value");
+ resolve_color_style_value(
+ &retained(value),
+ Rgba::from_packed(element_style.background_color()),
+ Some(&color_input),
+ )
+ }
+ property_id::BORDER_BOTTOM_COLOR => self.resolved_color(property, style.border_bottom_color()),
+ property_id::BORDER_LEFT_COLOR => self.resolved_color(property, style.border_left_color()),
+ property_id::BORDER_RIGHT_COLOR => self.resolved_color(property, style.border_right_color()),
+ property_id::BORDER_TOP_COLOR => self.resolved_color(property, style.border_top_color()),
+ property_id::BOX_SHADOW => {
+ let shadows = &style.effects().box_shadows;
+ // SAFETY: The list holds `length` shadows while the style lives.
+ let shadows = unsafe { ak::slice_from_raw_parts(shadows.pointer.cast_const(), shadows.length) };
+ style_value_for_shadow(SHADOW_TYPE_NORMAL, shadows, current)
+ }
+ property_id::CARET_COLOR => {
+ self.resolved_color(property, style.inherited_ui().caret_color.color.resolve(current_color))
+ }
+ property_id::COLOR => resolve_color_style_value(
+ &self.computed(property),
+ Rgba::from_packed(self.element_style.current_color()),
+ Some(&ColorResolutionInput::for_style(self.element_style)),
+ ),
+ property_id::FILL | property_id::FLOOD_COLOR | property_id::STOP_COLOR | property_id::STROKE => {
+ resolve_svg_color_style_value(&self.computed(property), &color_input)
+ }
+ property_id::COLUMN_RULE_COLOR => self.resolved_color(property, style.column_rule_color()),
+ property_id::OUTLINE_COLOR => self.resolved_color(property, style.outline_color()),
+ property_id::TEXT_DECORATION_COLOR => self.resolved_color(property, style.text_decoration_color()),
+ property_id::TEXT_SHADOW => {
+ let shadows = &style.inherited_text().text_shadow;
+ // SAFETY: The list holds `length` shadows while the style lives.
+ let shadows = unsafe { ak::slice_from_raw_parts(shadows.pointer.cast_const(), shadows.length) };
+ style_value_for_shadow(SHADOW_TYPE_TEXT, shadows, current)
+ }
+ property_id::BACKDROP_FILTER | property_id::FILTER => {
+ resolve_filter_style_value(&self.computed(property), current)
+ }
+ property_id::TOUCH_ACTION => resolve_touch_action_style_value(&self.computed(property)),
+
+ // -> line-height
+ // The resolved value is normal if the computed value is normal, or the used value otherwise.
+ property_id::LINE_HEIGHT => {
+ let line_height = self.computed(property);
+ if matches!(&*line_height, StyleValueData::Keyword { keyword } if *keyword == keyword::NORMAL) {
+ return line_height;
+ }
+ length_value(self.element_style.font().line_height_used().to_double())
+ }
+
+ property_id::HEIGHT => self.resolved_value_for_size(property, |size| size.height, |size| size.height),
+ property_id::WIDTH => self.resolved_value_for_size(property, |size| size.width, |size| size.width),
+ property_id::MARGIN_BOTTOM => {
+ self.resolved_value_for_margin(&principal_surround.margin.bottom, |metrics| metrics.margin.bottom)
+ }
+ property_id::MARGIN_LEFT => {
+ self.resolved_value_for_margin(&principal_surround.margin.left, |metrics| metrics.margin.left)
+ }
+ property_id::MARGIN_RIGHT => {
+ self.resolved_value_for_margin(&principal_surround.margin.right, |metrics| metrics.margin.right)
+ }
+ property_id::MARGIN_TOP => {
+ self.resolved_value_for_margin(&principal_surround.margin.top, |metrics| metrics.margin.top)
+ }
+ property_id::PADDING_BOTTOM => {
+ self.resolved_value_for_padding(&surround.padding.bottom, |metrics| metrics.padding.bottom)
+ }
+ property_id::PADDING_LEFT => {
+ self.resolved_value_for_padding(&surround.padding.left, |metrics| metrics.padding.left)
+ }
+ property_id::PADDING_RIGHT => {
+ self.resolved_value_for_padding(&surround.padding.right, |metrics| metrics.padding.right)
+ }
+ property_id::PADDING_TOP => {
+ self.resolved_value_for_padding(&surround.padding.top, |metrics| metrics.padding.top)
+ }
+
+ // NB: The computed value of a min or max sizing property resolves its anchor-size() functions, which layout
+ // resolves against an anchor box.
+ property_id::MAX_HEIGHT => self.resolved_min_or_max_size(property, FfiAnchorSizedProperty::MaxHeight),
+ property_id::MAX_WIDTH => self.resolved_min_or_max_size(property, FfiAnchorSizedProperty::MaxWidth),
+ property_id::MIN_HEIGHT => self.resolved_min_or_max_size(property, FfiAnchorSizedProperty::MinHeight),
+ property_id::MIN_WIDTH => self.resolved_min_or_max_size(property, FfiAnchorSizedProperty::MinWidth),
+
+ property_id::BOTTOM => {
+ self.resolved_value_for_inset(&inset.bottom, &inset.top, InsetAxis::Vertical, |metrics| {
+ metrics.inset.bottom
+ })
+ }
+ property_id::LEFT => {
+ self.resolved_value_for_inset(&inset.left, &inset.right, InsetAxis::Horizontal, |metrics| {
+ metrics.inset.left
+ })
+ }
+ property_id::RIGHT => {
+ self.resolved_value_for_inset(&inset.right, &inset.left, InsetAxis::Horizontal, |metrics| {
+ metrics.inset.right
+ })
+ }
+ property_id::TOP => {
+ self.resolved_value_for_inset(&inset.top, &inset.bottom, InsetAxis::Vertical, |metrics| {
+ metrics.inset.top
+ })
+ }
+
+ // -> A resolved value special case property defined in another specification
+ // As defined in the relevant specification.
+ property_id::TRANSFORM => self.resolved_transform(),
+ property_id::TRANSFORM_ORIGIN => {
+ // https://drafts.csswg.org/css-transforms/#transform-origin-property
+ // The transform-origin property is a resolved value special case property like height. [CSSOM]
+ let values = style.transform();
+ style_value_for_transform_origin(
+ handle_value(&values.transform_origin_x).expect("transform-origin has an x offset"),
+ handle_value(&values.transform_origin_y).expect("transform-origin has a y offset"),
+ handle_value(&values.transform_origin_z),
+ self.reference_box_if_used(),
+ )
+ }
+ property_id::PERSPECTIVE_ORIGIN => {
+ // https://drafts.csswg.org/css-transforms-2/#perspective-origin-property
+ // The perspective-origin property is a resolved value special case property like height. [CSSOM]
+ let Some(reference_box) = self.reference_box_if_used() else {
+ return self.computed(property);
+ };
+ let values = style.transform();
+ style_value_for_transform_origin(
+ handle_value(&values.perspective_origin_x).expect("perspective-origin has an x offset"),
+ handle_value(&values.perspective_origin_y).expect("perspective-origin has a y offset"),
+ None,
+ Some(reference_box),
+ )
+ }
+ property_id::ANIMATION_DURATION => self.resolved_animation_duration(),
+
+ // If the border-style corresponding to a given border-width is none or hidden, then the used width is 0.
+ // https://drafts.csswg.org/css-backgrounds/#border-width
+ // NB: We do this adjustment when assigning to ComputedValues, so read from there.
+ property_id::BORDER_BOTTOM_WIDTH => length_value(style.border_bottom_width().to_double()),
+ property_id::BORDER_LEFT_WIDTH => length_value(style.border_left_width().to_double()),
+ property_id::BORDER_RIGHT_WIDTH => length_value(style.border_right_width().to_double()),
+ property_id::BORDER_TOP_WIDTH => length_value(style.border_top_width().to_double()),
+
+ // -> Any other property
+ // The resolved value is the computed value.
+ property_id::_WEBKIT_TEXT_FILL_COLOR => {
+ self.resolved_color(property, style.inherited_text().webkit_text_fill_color)
+ }
+ property_id::LETTER_SPACING => {
+ // https://drafts.csswg.org/css-text-4/#letter-spacing-property
+ // For legacy reasons, a computed letter-spacing of zero yields a resolved value (getComputedStyle()
+ // return value) of normal.
+ if style.letter_spacing().raw_value() == 0 {
+ return keyword_value(keyword::NORMAL);
+ }
+ self.computed(property)
+ }
+ _ => {
+ // For grid-template-columns and grid-template-rows the resolved value is the used value.
+ // https://www.w3.org/TR/css-grid-2/#resolved-track-list-standalone
+ if matches!(
+ property,
+ property_id::GRID_TEMPLATE_COLUMNS | property_id::GRID_TEMPLATE_ROWS
+ ) && has_committed_box(self.host, self.node)
+ {
+ let tracks = crate::painting::ffi::render_state_paintable_used_grid_tracks(
+ self.host,
+ self.node,
+ property == property_id::GRID_TEMPLATE_COLUMNS,
+ );
+ if !tracks.is_null() {
+ // SAFETY: The call hands over one strong reference.
+ return unsafe { StyleValueArc::from_raw(tracks.cast()) };
+ }
+ }
+
+ if !property_is_shorthand(property) {
+ return self.computed(property);
+ }
+
+ // Handle shorthands in a generic way
+ let longhand_ids = longhands_for_shorthand(property);
+ let longhand_values = longhand_ids
+ .iter()
+ .map(|&longhand| RetainedStyleValueData::from_arc(self.resolved_value(longhand)))
+ .collect();
+ StyleValueArc::new(StyleValueData::Shorthand(StyleValueBox::new(ShorthandPayload {
+ shorthand_property: property,
+ sub_properties: RetainedPropertyIdList::from_property_ids(longhand_ids.to_vec()),
+ values: RetainedStyleValueDataList::from_retained_values(longhand_values),
+ })))
+ }
+ }
+ }
+}
+
+/// The resolved value of `property` for the element of a box, as one strong reference.
+///
+/// # Safety
+/// The query must name a live host, nodes of its layout tree and a live style.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_resolved_value_of_box(
+ query: &FfiResolvedValueBox,
+ property: u16,
+) -> *const StyleValueData {
+ // SAFETY: Guaranteed by the caller.
+ let (host, element_style) = unsafe {
+ (
+ &*query.host.cast::<DocumentHost>(),
+ ComputedValuesView::of_record_groups(&*query.element_style.cast::<StyleRecordGroups>()),
+ )
+ };
+ let node = NodeSlotId { index: query.node };
+ let principal_node = NodeSlotId {
+ index: query.principal_node,
+ };
+ let resolved_box = ResolvedValueBox {
+ query,
+ host,
+ node,
+ principal_node,
+ style: node_style(host, node),
+ principal_style: node_style(host, principal_node),
+ element_style,
+ };
+ StyleValueArc::into_raw(resolved_box.resolved_value(property))
+}
diff --git a/Libraries/LibWeb/Rust/src/layout/script_entries.rs b/Libraries/LibWeb/Rust/src/layout/script_entries.rs
index 10f4bf16282..9b70de0aee6 100644
--- a/Libraries/LibWeb/Rust/src/layout/script_entries.rs
+++ b/Libraries/LibWeb/Rust/src/layout/script_entries.rs
@@ -661,7 +661,6 @@ pub unsafe extern "C" fn layout_script_find_matching_text(
/// A min or max sizing property, whose anchor-size() functions the abspos engine resolves.
#[repr(u8)]
#[derive(Clone, Copy)]
-#[expect(dead_code, reason = "C++ constructs the variants")]
pub enum FfiAnchorSizedProperty {
MinWidth,
MinHeight,