use std::rc::Rc;
use std::sync::atomic::{AtomicU64, Ordering};
use super::*;
use crate::dom::ElementId;
use crate::layout::assets::DocumentPageIndex;
use crate::layout::text_paint::TextInlineSpan;
#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) struct PositionedPaintLayer {
pub(in crate::layout) page_index: usize,
pub(in crate::layout) transaction_depth: usize,
pub(in crate::layout) source_element: Option<crate::dom::ElementId>,
pub(in crate::layout) source_style: ComputedStyle,
pub(in crate::layout) source_style_identity: usize,
pub(in crate::layout) source_box: InlineStaticPositionBoxSource,
pub(in crate::layout) multicol_fragment_index: Option<usize>,
pub(in crate::layout) source_is_target: bool,
pub(in crate::layout) stack_level: StackLevel,
pub(in crate::layout) context: PaintStackingContext,
pub(in crate::layout) links: Vec<RenderedLink>,
pub(in crate::layout) escaped_atom_replay: EscapedAtomReplay,
pub(in crate::layout) overflow_clip_containing_block:
Option<PositionedContainingBlockScopeDepth>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) enum PositionedContainingBlockScopeDepth {
Absolute(usize),
Fixed(usize),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) struct PositionedOverflowClipBoundary {
absolute_depth: usize,
fixed_depth: usize,
}
impl PositionedOverflowClipBoundary {
pub(in crate::layout) const fn new(absolute_depth: usize, fixed_depth: usize) -> Self {
Self {
absolute_depth,
fixed_depth,
}
}
pub(in crate::layout) const fn applies_to(self, layer: &PositionedPaintLayer) -> bool {
self.applies_to_containing_block(layer.overflow_clip_containing_block)
}
const fn applies_to_containing_block(
self,
containing_block: Option<PositionedContainingBlockScopeDepth>,
) -> bool {
match containing_block {
None => true,
Some(PositionedContainingBlockScopeDepth::Absolute(depth)) => {
depth > self.absolute_depth
}
Some(PositionedContainingBlockScopeDepth::Fixed(depth)) => depth > self.fixed_depth,
}
}
}
#[cfg(test)]
mod positioned_overflow_clip_boundary_tests {
use super::*;
#[test]
fn clip_applies_only_when_the_containing_block_is_inside_its_boundary() {
let boundary = PositionedOverflowClipBoundary::new(2, 3);
assert!(boundary.applies_to_containing_block(None));
assert!(
!boundary.applies_to_containing_block(Some(
PositionedContainingBlockScopeDepth::Absolute(2),
))
);
assert!(
boundary.applies_to_containing_block(Some(
PositionedContainingBlockScopeDepth::Absolute(3),
))
);
assert!(
!boundary
.applies_to_containing_block(Some(PositionedContainingBlockScopeDepth::Fixed(3),))
);
assert!(
boundary
.applies_to_containing_block(Some(PositionedContainingBlockScopeDepth::Fixed(4),))
);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(in crate::layout) struct PositionedPaintCommitKey {
source_element: crate::dom::ElementId,
source_box: InlineStaticPositionBoxSource,
source_style_identity: usize,
multicol_fragment_index: Option<usize>,
}
impl PositionedPaintLayer {
pub(in crate::layout) fn commit_key(&self) -> Option<PositionedPaintCommitKey> {
self.source_element
.map(|source_element| PositionedPaintCommitKey {
source_element,
source_box: self.source_box,
source_style_identity: self.source_style_identity,
multicol_fragment_index: self.multicol_fragment_index,
})
}
pub(in crate::layout) fn with_multicol_fragment_index(mut self, index: usize) -> Self {
self.multicol_fragment_index = Some(index);
self
}
pub(in crate::layout) fn translated(mut self, offset: PaintTranslation) -> Self {
self.context = self.context.translated(offset);
self.links = self
.links
.into_iter()
.map(|link| link.translated(offset))
.collect();
self
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(in crate::layout) enum EscapedAtomAxisReplay {
RetainPageCoordinate,
FollowAtomicInline,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(in crate::layout) enum EscapedAtomHorizontalReplay {
RetainPageCoordinate,
FollowFromAtomicCapture,
FollowFromPageContainingBlock(PageInlinePosition),
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(in crate::layout) struct EscapedAtomReplayPolicy {
pub(in crate::layout) horizontal: EscapedAtomHorizontalReplay,
pub(in crate::layout) vertical: EscapedAtomAxisReplay,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(in crate::layout) struct EscapedAtomReplayTransform {
pub(in crate::layout) source_origin: PaintPoint,
pub(in crate::layout) horizontal: EscapedAtomAxisReplay,
pub(in crate::layout) vertical: EscapedAtomAxisReplay,
}
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub(in crate::layout) enum EscapedAtomReplay {
#[default]
RetainPageCoordinates,
Pending(EscapedAtomReplayPolicy),
Resolved(EscapedAtomReplayTransform),
}
impl EscapedAtomReplay {
pub(in crate::layout) fn none() -> Self {
Self::default()
}
pub(in crate::layout) fn normal_flow_fragment() -> Self {
Self::Pending(EscapedAtomReplayPolicy {
horizontal: EscapedAtomHorizontalReplay::FollowFromAtomicCapture,
vertical: EscapedAtomAxisReplay::FollowAtomicInline,
})
}
pub(in crate::layout) fn for_positioned_box(
containing_block: ContainingBlock,
containing_block_is_atom_local: bool,
uses_static_x: bool,
uses_static_y: bool,
) -> Self {
let follows_y = containing_block_is_atom_local || uses_static_y;
Self::Pending(EscapedAtomReplayPolicy {
horizontal: if containing_block_is_atom_local {
EscapedAtomHorizontalReplay::FollowFromAtomicCapture
} else if uses_static_x {
EscapedAtomHorizontalReplay::FollowFromPageContainingBlock(PageInlinePosition::new(
containing_block.x(),
))
} else {
EscapedAtomHorizontalReplay::RetainPageCoordinate
},
vertical: if follows_y {
EscapedAtomAxisReplay::FollowAtomicInline
} else {
EscapedAtomAxisReplay::RetainPageCoordinate
},
})
}
pub(in crate::layout) fn resolve_from_capture_origin(self, capture_origin: PaintPoint) -> Self {
match self {
Self::Pending(policy) => {
let (horizontal, source_x) = match policy.horizontal {
EscapedAtomHorizontalReplay::RetainPageCoordinate => (
EscapedAtomAxisReplay::RetainPageCoordinate,
capture_origin.x,
),
EscapedAtomHorizontalReplay::FollowFromAtomicCapture => {
(EscapedAtomAxisReplay::FollowAtomicInline, capture_origin.x)
}
EscapedAtomHorizontalReplay::FollowFromPageContainingBlock(origin) => {
(EscapedAtomAxisReplay::FollowAtomicInline, origin.points())
}
};
Self::Resolved(EscapedAtomReplayTransform {
source_origin: PaintPoint::new(source_x, capture_origin.y),
horizontal,
vertical: policy.vertical,
})
}
Self::RetainPageCoordinates | Self::Resolved(_) => self,
}
}
pub(in crate::layout) fn translation_to(self, final_origin: PaintPoint) -> PaintTranslation {
debug_assert!(
!matches!(self, Self::Pending(_)),
"escaped atomic-inline replay must be resolved at capture"
);
let Self::Resolved(transform) = self else {
return PaintTranslation::identity();
};
PaintTranslation::new(
match transform.horizontal {
EscapedAtomAxisReplay::RetainPageCoordinate => 0.0,
EscapedAtomAxisReplay::FollowAtomicInline => {
final_origin.x - transform.source_origin.x
}
},
match transform.vertical {
EscapedAtomAxisReplay::RetainPageCoordinate => 0.0,
EscapedAtomAxisReplay::FollowAtomicInline => {
final_origin.y - transform.source_origin.y
}
},
)
}
pub(in crate::layout) fn pending_in_enclosing_atomic_space(self) -> Self {
let (horizontal, vertical) = match self {
Self::Resolved(transform) => (
match transform.horizontal {
EscapedAtomAxisReplay::RetainPageCoordinate => {
EscapedAtomHorizontalReplay::RetainPageCoordinate
}
EscapedAtomAxisReplay::FollowAtomicInline => {
EscapedAtomHorizontalReplay::FollowFromAtomicCapture
}
},
transform.vertical,
),
Self::RetainPageCoordinates => (
EscapedAtomHorizontalReplay::RetainPageCoordinate,
EscapedAtomAxisReplay::RetainPageCoordinate,
),
Self::Pending(policy) => (
match policy.horizontal {
EscapedAtomHorizontalReplay::RetainPageCoordinate => {
EscapedAtomHorizontalReplay::RetainPageCoordinate
}
EscapedAtomHorizontalReplay::FollowFromAtomicCapture
| EscapedAtomHorizontalReplay::FollowFromPageContainingBlock(_) => {
EscapedAtomHorizontalReplay::FollowFromAtomicCapture
}
},
policy.vertical,
),
};
Self::Pending(EscapedAtomReplayPolicy {
horizontal,
vertical,
})
}
pub(in crate::layout) fn replay_page_index(
self,
atom_page_index: usize,
positioned_page_index: usize,
) -> usize {
match self {
Self::Resolved(EscapedAtomReplayTransform {
vertical: EscapedAtomAxisReplay::FollowAtomicInline,
..
}) => atom_page_index,
Self::RetainPageCoordinates
| Self::Pending(_)
| Self::Resolved(EscapedAtomReplayTransform {
vertical: EscapedAtomAxisReplay::RetainPageCoordinate,
..
}) => positioned_page_index,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) struct FixedPaintLayer {
pub(in crate::layout) source_element: crate::dom::ElementId,
pub(in crate::layout) source_style: ComputedStyle,
pub(in crate::layout) stack_level: StackLevel,
pub(in crate::layout) context: PaintStackingContext,
pub(in crate::layout) links: Vec<RenderedLink>,
}
#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) struct StackingContextPolicy {
pub(in crate::layout) parent_band: PaintBand,
pub(in crate::layout) stack_level: StackLevel,
pub(in crate::layout) context_kind: StackingContextKind,
pub(in crate::layout) child_layer_policy: ChildLayerPolicy,
pub(in crate::layout) is_real_stacking_context: bool,
pub(in crate::layout) is_fake_context: bool,
pub(in crate::layout) creates_compositing_group: bool,
pub(in crate::layout) establishes_containing_block: bool,
pub(in crate::layout) captures_positioned_descendants: bool,
pub(in crate::layout) effects: PaintEffects,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) enum StackingContextKind {
None,
Real,
FakeAtomic,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::layout) enum FlexGridItemPaintContext {
SamePageUnfragmented,
FragmentedOrNested,
}
impl FlexGridItemPaintContext {
fn static_parent_band(self) -> PaintBand {
match self {
Self::SamePageUnfragmented => PaintBand::Inline,
Self::FragmentedOrNested => PaintBand::InFlowBlock,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) enum ChildLayerPolicy {
CaptureAll,
CaptureAutoLevel,
EscapeAll,
}
impl StackingContextPolicy {
pub(in crate::layout) fn for_positioned(
element: &Element,
style: &ComputedStyle,
bounds: PaintClip,
) -> Self {
let effects = assets::paint_effects_for_element_box(element, style, bounds);
let is_real_stacking_context =
matches!(&style.position, Position::Fixed | Position::Sticky)
|| style.z_index.establishes_stacking_context()
|| style_creates_effect_stacking_context_with_containment(
style,
&effects,
property_containment_applies_to_element(element, style),
);
let is_fake_context = !is_real_stacking_context
&& matches!(&style.position, Position::Relative | Position::Absolute);
Self {
parent_band: StackLevel::from_optional_z_index(style.z_index.stack_level())
.paint_band(),
stack_level: StackLevel::from_optional_z_index(style.z_index.stack_level()),
context_kind: if is_real_stacking_context {
StackingContextKind::Real
} else if is_fake_context {
StackingContextKind::FakeAtomic
} else {
StackingContextKind::None
},
child_layer_policy: if is_real_stacking_context {
ChildLayerPolicy::CaptureAll
} else {
ChildLayerPolicy::EscapeAll
},
is_real_stacking_context,
is_fake_context,
creates_compositing_group: effects.needs_group(),
establishes_containing_block: matches!(
&style.position,
Position::Relative | Position::Absolute | Position::Fixed | Position::Sticky
) || style.has_transform_or_preserve_3d(),
captures_positioned_descendants: is_real_stacking_context,
effects,
}
}
pub(in crate::layout) fn for_non_positioned_effect(
element: &Element,
style: &ComputedStyle,
bounds: PaintClip,
) -> Self {
Self::for_non_positioned_effect_with_geometry(
element,
style,
assets::PrincipalPaintGeometry::css_layout(bounds),
)
}
pub(in crate::layout) fn for_non_positioned_effect_with_geometry(
element: &Element,
style: &ComputedStyle,
geometry: assets::PrincipalPaintGeometry,
) -> Self {
let effects = assets::paint_effects_for_principal_box(style, geometry);
Self::for_non_positioned_effect_with_effects(
style,
effects,
property_containment_applies_to_element(element, style),
)
}
pub(in crate::layout) fn for_non_positioned_style_effect(
style: &ComputedStyle,
bounds: PaintClip,
) -> Self {
let effects = assets::paint_effects_for_box(style, bounds);
Self::for_non_positioned_effect_with_effects(
style,
effects,
property_containment_applies_to_style(style),
)
}
pub(in crate::layout) fn for_non_positioned_effect_with_effects(
style: &ComputedStyle,
effects: PaintEffects,
containment_applies: bool,
) -> Self {
let in_flow_positioned = matches!(&style.position, Position::Relative | Position::Sticky);
let stack_level = if in_flow_positioned {
StackLevel::from_optional_z_index(style.z_index.stack_level())
} else {
StackLevel::Auto
};
let is_real_stacking_context = matches!(&style.position, Position::Sticky)
|| (style.position == Position::Relative
&& style.z_index.establishes_stacking_context())
|| style_creates_effect_stacking_context_with_containment(
style,
&effects,
containment_applies,
);
let is_fake_context = style.position == Position::Relative && !is_real_stacking_context;
Self {
parent_band: if in_flow_positioned {
stack_level.paint_band()
} else {
PaintBand::InFlowBlock
},
stack_level,
context_kind: if is_real_stacking_context {
StackingContextKind::Real
} else if is_fake_context {
StackingContextKind::FakeAtomic
} else {
StackingContextKind::None
},
child_layer_policy: if is_real_stacking_context {
ChildLayerPolicy::CaptureAll
} else if is_fake_context {
ChildLayerPolicy::CaptureAutoLevel
} else {
ChildLayerPolicy::EscapeAll
},
is_real_stacking_context,
is_fake_context,
creates_compositing_group: effects.needs_group(),
establishes_containing_block: style.has_transform_or_preserve_3d(),
captures_positioned_descendants: is_real_stacking_context,
effects,
}
}
pub(in crate::layout) fn for_atomic(
style: &ComputedStyle,
parent_band: PaintBand,
bounds: PaintClip,
) -> Self {
Self::for_atomic_with_geometry(
style,
parent_band,
assets::PrincipalPaintGeometry::css_layout(bounds),
)
}
pub(in crate::layout) fn for_atomic_with_geometry(
style: &ComputedStyle,
parent_band: PaintBand,
geometry: assets::PrincipalPaintGeometry,
) -> Self {
let effects = assets::paint_effects_for_principal_box(style, geometry);
let in_flow_positioned = matches!(&style.position, Position::Relative | Position::Sticky);
let stack_level = if in_flow_positioned {
StackLevel::from_optional_z_index(style.z_index.stack_level())
} else {
StackLevel::Auto
};
let is_real_stacking_context = matches!(&style.position, Position::Sticky)
|| (style.position == Position::Relative
&& style.z_index.establishes_stacking_context())
|| style_creates_effect_stacking_context(style, &effects);
Self {
parent_band: if is_real_stacking_context || in_flow_positioned {
stack_level.paint_band()
} else {
parent_band
},
stack_level,
context_kind: if is_real_stacking_context {
StackingContextKind::Real
} else {
StackingContextKind::FakeAtomic
},
child_layer_policy: if is_real_stacking_context {
ChildLayerPolicy::CaptureAll
} else {
ChildLayerPolicy::EscapeAll
},
is_real_stacking_context,
is_fake_context: true,
creates_compositing_group: effects.needs_group(),
establishes_containing_block: in_flow_positioned
|| style.has_transform_or_preserve_3d(),
captures_positioned_descendants: is_real_stacking_context,
effects,
}
}
pub(in crate::layout) fn for_inline_svg_root(
style: &ComputedStyle,
parent_band: PaintBand,
bounds: PaintClip,
) -> Self {
Self::for_inline_svg_root_with_geometry(
style,
parent_band,
assets::PrincipalPaintGeometry::css_layout(bounds),
)
}
pub(in crate::layout) fn for_inline_svg_root_with_geometry(
style: &ComputedStyle,
parent_band: PaintBand,
geometry: assets::PrincipalPaintGeometry,
) -> Self {
let mut policy = Self::for_atomic_with_geometry(style, parent_band, geometry);
policy.context_kind = StackingContextKind::Real;
policy.child_layer_policy = ChildLayerPolicy::CaptureAll;
policy.is_real_stacking_context = true;
policy.is_fake_context = false;
policy.creates_compositing_group = true;
policy.captures_positioned_descendants = true;
policy.effects.isolation = true;
policy
}
pub(in crate::layout) fn for_flex_item(style: &ComputedStyle, bounds: PaintClip) -> Self {
Self::for_flex_or_grid_item(
style,
bounds,
FlexGridItemPaintContext::SamePageUnfragmented,
)
}
pub(in crate::layout) fn for_fragmented_flex_item(
style: &ComputedStyle,
bounds: PaintClip,
) -> Self {
Self::for_flex_or_grid_item(style, bounds, FlexGridItemPaintContext::FragmentedOrNested)
}
fn for_flex_or_grid_item(
style: &ComputedStyle,
bounds: PaintClip,
paint_context: FlexGridItemPaintContext,
) -> Self {
let stack_level = StackLevel::from_optional_z_index(style.z_index.stack_level());
let effects = assets::paint_effects_for_box(style, bounds);
let in_flow_positioned = matches!(&style.position, Position::Relative | Position::Sticky);
let is_real_stacking_context = matches!(&style.position, Position::Sticky)
|| style.z_index.establishes_stacking_context()
|| style_creates_effect_stacking_context(style, &effects);
let is_fake_context = style.position == Position::Relative && !is_real_stacking_context;
Self {
parent_band: if is_real_stacking_context || in_flow_positioned {
stack_level.paint_band()
} else {
paint_context.static_parent_band()
},
stack_level,
context_kind: if is_real_stacking_context {
StackingContextKind::Real
} else if is_fake_context {
StackingContextKind::FakeAtomic
} else {
StackingContextKind::None
},
child_layer_policy: if is_real_stacking_context {
ChildLayerPolicy::CaptureAll
} else {
ChildLayerPolicy::EscapeAll
},
is_real_stacking_context,
is_fake_context,
creates_compositing_group: effects.needs_group(),
establishes_containing_block: in_flow_positioned
|| style.has_transform_or_preserve_3d(),
captures_positioned_descendants: is_real_stacking_context,
effects,
}
}
pub(in crate::layout) fn for_grid_item(style: &ComputedStyle, bounds: PaintClip) -> Self {
Self::for_flex_item(style, bounds)
}
pub(in crate::layout) fn for_fragmented_grid_item(
style: &ComputedStyle,
bounds: PaintClip,
) -> Self {
Self::for_fragmented_flex_item(style, bounds)
}
pub(in crate::layout) fn style_needs_non_positioned_scope(
element: &Element,
style: &ComputedStyle,
) -> bool {
matches!(&style.position, Position::Relative | Position::Sticky)
|| style_creates_effect_stacking_context_with_containment(
style,
&assets::paint_effects_for_element_box(
element,
style,
PaintClip::from_paint_rect(paint_space_rect(0.0, 0.0, 0.0, 0.0)),
),
property_containment_applies_to_element(element, style),
)
|| used_overflow_clips_element(element, style)
}
}
pub(in crate::layout) fn style_creates_effect_stacking_context(
style: &ComputedStyle,
effects: &PaintEffects,
) -> bool {
style_creates_effect_stacking_context_with_containment(
style,
effects,
property_containment_applies_to_style(style),
)
}
fn style_creates_effect_stacking_context_with_containment(
style: &ComputedStyle,
effects: &PaintEffects,
containment_applies: bool,
) -> bool {
effects.opacity < 1.0
|| effects.transform.is_some()
|| effects.descendant_projective_3d_transform.is_some()
|| effects.three_d_participation
!= crate::document::paint::effects::ThreeDParticipation::Flat
|| effects.clip_path.is_active()
|| effects.mask.is_active()
|| effects.filter.is_active()
|| effects.blend_mode != PaintBlendMode::Normal
|| effects.isolation
|| style.isolation == Isolation::Isolate
|| style.mix_blend_mode != MixBlendMode::Normal
|| !matches!(style.filter, FilterValue::None)
|| style.clip_path != ClipPath::None
|| !matches!(style.mask, MaskValue::None)
|| (containment_applies && (style.contain.layout || style.contain.paint))
|| matches!(
style.content_visibility,
ContentVisibility::Auto | ContentVisibility::Hidden
)
|| style.will_change.opacity
|| style.will_change.transform
|| style.will_change.filter
|| style.will_change.clip_path
|| style.will_change.mask
|| style.will_change.mix_blend_mode
|| style.will_change.isolation
|| style.will_change.contain
}
pub(in crate::layout) type NamedStringAssignment = PageAssignment<PageAssignmentValue>;
#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) struct CapturedPageAssignment {
pub(in crate::layout) name: String,
pub(in crate::layout) value: PageAssignmentValue,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(in crate::layout) struct AssignmentId(pub(in crate::layout) usize);
#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) struct PageAssignment<T> {
pub(in crate::layout) id: AssignmentId,
pub(in crate::layout) value: T,
pub(in crate::layout) placement: AssignmentPlacement,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(in crate::layout) struct AssignmentPlacement {
pub(in crate::layout) page_index: usize,
pub(in crate::layout) starts_page_fragment: bool,
pub(in crate::layout) border_box: Option<PaintClip>,
}
#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) struct FragmentPageValue {
pub(in crate::layout) page_name: Option<String>,
pub(in crate::layout) specified: bool,
}
impl FragmentPageValue {
pub(in crate::layout) fn unspecified() -> Self {
Self {
page_name: None,
specified: false,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) struct FragmentPageMetadata {
pub(in crate::layout) page_index: usize,
pub(in crate::layout) source_border_box: Option<PaintClip>,
pub(in crate::layout) starts_page_fragment: bool,
pub(in crate::layout) continues_from_previous_page: bool,
pub(in crate::layout) continues_to_next_page: bool,
pub(in crate::layout) first_page_value: FragmentPageValue,
pub(in crate::layout) last_page_value: FragmentPageValue,
pub(in crate::layout) assignment_ids: Vec<AssignmentId>,
}
impl FragmentPageMetadata {
pub(in crate::layout) fn new(
page_index: usize,
source_border_box: Option<PaintClip>,
starts_page_fragment: bool,
) -> Self {
Self {
page_index,
source_border_box,
starts_page_fragment,
continues_from_previous_page: false,
continues_to_next_page: false,
first_page_value: FragmentPageValue::unspecified(),
last_page_value: FragmentPageValue::unspecified(),
assignment_ids: Vec::new(),
}
}
pub(in crate::layout) fn empty(page_index: usize) -> Self {
Self::new(page_index, None, false)
}
pub(in crate::layout) fn assignment_placement(&self) -> AssignmentPlacement {
AssignmentPlacement {
page_index: self.page_index,
starts_page_fragment: self.starts_page_fragment,
border_box: self.source_border_box,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) enum PageAssignmentValue {
GeneratedContent(Vec<page_generated::PageMarginContentItem>),
RunningElement(Box<RunningElementCapture>),
}
#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) struct RunningElementCapture {
pub(in crate::layout) fallback_text: String,
pub(in crate::layout) content_parts: Vec<GeneratedContentPart>,
pub(in crate::layout) element: Element,
pub(in crate::layout) style: Box<ComputedStyle>,
pub(in crate::layout) counter_set: CounterSet,
pub(in crate::layout) quote_depth: usize,
}
#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) struct ListMarker {
pub(in crate::layout) source_element: Option<ElementId>,
pub(in crate::layout) text: String,
pub(in crate::layout) image: Option<MarkerImage>,
pub(in crate::layout) style: ComputedStyle,
pub(in crate::layout) position: ListStylePosition,
pub(in crate::layout) positioning_direction: Direction,
pub(in crate::layout) suffix_space: bool,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(in crate::layout) struct OutsideMarkerAnchor {
pub(in crate::layout) principal_line_inline_span: PageInlineSpan,
pub(in crate::layout) formatted_line_block_start: PageTopBlockPosition,
pub(in crate::layout) alphabetic_baseline: PageTopBlockPosition,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(in crate::layout) struct OutsideMarkerFallbackCandidate {
pub(in crate::layout) containing_inline_span: PageInlineSpan,
pub(in crate::layout) fallback_line_block_span: PageBlockSpan,
pub(in crate::layout) alphabetic_baseline: PageTopBlockPosition,
}
#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) struct ResolvedOutsideMarkerPaint {
pub(in crate::layout) marker: ListMarker,
pub(in crate::layout) list_item_style: ComputedStyle,
pub(in crate::layout) anchor: OutsideMarkerAnchor,
pub(in crate::layout) page: DocumentPageIndex,
pub(in crate::layout) fragment: PaintFragment,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) enum OutsideMarkerPaintOwner {
CurrentPaintScope,
ListItem,
}
impl OutsideMarkerPaintOwner {
pub(in crate::layout) fn for_principal_line_block(style: &ComputedStyle) -> Self {
if matches!(style.position, Position::Relative | Position::Sticky) {
Self::ListItem
} else {
Self::CurrentPaintScope
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) enum DeferredOutsideMarkerPaintState {
AwaitingAnchor,
Capturing,
Resolved(Box<ResolvedOutsideMarkerPaint>),
PaintedInPlace,
}
#[derive(Debug, Clone)]
pub(in crate::layout) struct PendingOutsideMarkerAnchor {
pub(in crate::layout) marker: ListMarker,
pub(in crate::layout) list_item_style: ComputedStyle,
pub(in crate::layout) fallback: OutsideMarkerFallbackCandidate,
pub(in crate::layout) paint: DeferredOutsideMarkerPaintState,
}
#[derive(Debug, Clone, Default)]
pub(in crate::layout) struct PendingOutsideMarkerAnchors {
anchors: Vec<PendingOutsideMarkerAnchor>,
}
#[must_use = "suspended outside-marker anchors must be restored after scratch layout"]
#[derive(Debug)]
pub(in crate::layout) struct SuspendedOutsideMarkerAnchors(PendingOutsideMarkerAnchors);
impl PendingOutsideMarkerAnchors {
pub(in crate::layout) fn push(&mut self, anchor: PendingOutsideMarkerAnchor) {
self.anchors.push(anchor);
}
pub(in crate::layout) fn pop(&mut self) -> Option<PendingOutsideMarkerAnchor> {
self.anchors.pop()
}
pub(in crate::layout) fn iter(&self) -> impl Iterator<Item = &PendingOutsideMarkerAnchor> {
self.anchors.iter()
}
pub(in crate::layout) fn begin_paint_capture(&mut self, index: usize) {
debug_assert!(
matches!(
self.anchors[index].paint,
DeferredOutsideMarkerPaintState::AwaitingAnchor
),
"only an unresolved marker anchor can begin paint capture"
);
self.anchors[index].paint = DeferredOutsideMarkerPaintState::Capturing;
}
pub(in crate::layout) fn finish_paint_capture(
&mut self,
index: usize,
paint: ResolvedOutsideMarkerPaint,
) {
debug_assert!(
matches!(
self.anchors[index].paint,
DeferredOutsideMarkerPaintState::Capturing
),
"only a marker being captured can receive its paint fragment"
);
self.anchors[index].paint = DeferredOutsideMarkerPaintState::Resolved(Box::new(paint));
}
pub(in crate::layout) fn mark_painted_in_place(&mut self, index: usize) {
debug_assert!(
matches!(
self.anchors[index].paint,
DeferredOutsideMarkerPaintState::AwaitingAnchor
),
"only an unresolved marker anchor can paint in its current owner"
);
self.anchors[index].paint = DeferredOutsideMarkerPaintState::PaintedInPlace;
}
pub(in crate::layout) fn suspend(&mut self) -> SuspendedOutsideMarkerAnchors {
SuspendedOutsideMarkerAnchors(std::mem::take(self))
}
pub(in crate::layout) fn restore(&mut self, suspended: SuspendedOutsideMarkerAnchors) {
debug_assert!(
self.anchors.is_empty(),
"a scratch layout must finalize its local outside-marker anchors"
);
*self = suspended.0;
}
pub(in crate::layout) fn is_empty(&self) -> bool {
self.anchors.is_empty()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) enum NestedInlinePaintFloatPolicy {
ReapplyActiveFloatBands,
PreserveResolvedGeometry,
}
impl ListMarker {
pub(in crate::layout) fn has_in_flow_content(&self) -> bool {
self.image.is_some() || !crate::text::trim_css_collapsible_whitespace(&self.text).is_empty()
}
pub(in crate::layout) fn participates_in_first_line(&self) -> bool {
self.position == ListStylePosition::Inside
}
pub(in crate::layout) fn paints_outside(&self) -> bool {
self.position == ListStylePosition::Outside && !self.participates_in_first_line()
}
pub(in crate::layout) fn follows_content_in_first_line(&self) -> bool {
false
}
}
#[derive(Debug, Clone)]
pub(in crate::layout) struct MarkerImage {
pub(in crate::layout) decoded: DecodedPngImage,
pub(in crate::layout) svg: Option<SharedSvgAsset>,
pub(in crate::layout) width: f32,
pub(in crate::layout) height: f32,
}
impl PartialEq for MarkerImage {
fn eq(&self, other: &Self) -> bool {
self.decoded == other.decoded
&& self.width == other.width
&& self.height == other.height
&& self.svg.as_ref().map(Rc::as_ptr) == other.svg.as_ref().map(Rc::as_ptr)
}
}
#[derive(Debug, Clone)]
pub(in crate::layout) struct InlineWord {
pub(in crate::layout) text: String,
pub(in crate::layout) style: InlineStyle,
pub(in crate::layout) baseline_shift: f32,
pub(in crate::layout) visual_offset: InlineVisualOffset,
pub(in crate::layout) link_target: Option<Rc<str>>,
pub(in crate::layout) mergeable: bool,
pub(in crate::layout) source: InlineTextSource,
pub(in crate::layout) hanging_edges: InlineHangingEdges,
pub(in crate::layout) excluded_positioning_geometry_source:
Option<InlinePositioningContainingBlockId>,
pub(in crate::layout) ancestor_inline_decorations: Rc<[InlineAncestorDecoration]>,
}
pub(in crate::layout) type InlineStyle = Rc<ComputedStyle>;
#[derive(Debug, Clone, Copy)]
pub(in crate::layout) struct InlineBoundaryPolicy {
allows_soft_wrap: bool,
}
impl InlineBoundaryPolicy {
fn from_style(style: &ComputedStyle) -> Self {
Self {
allows_soft_wrap: style.allows_soft_wrap(),
}
}
pub(in crate::layout) fn allows_soft_wrap(self) -> bool {
self.allows_soft_wrap
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) enum InlineScopeLineRelativeAlignment {
Top,
Bottom,
}
impl InlineScopeLineRelativeAlignment {
pub(in crate::layout) fn from_baseline_shift(baseline_shift: &BaselineShift) -> Option<Self> {
match baseline_shift {
BaselineShift::Top => Some(Self::Top),
BaselineShift::Bottom => Some(Self::Bottom),
BaselineShift::LengthPercentage(_)
| BaselineShift::Super
| BaselineShift::Sub
| BaselineShift::Center => None,
}
}
}
#[derive(Debug)]
pub(in crate::layout) struct InlineTrackingScope {
parent: Option<Rc<Self>>,
depth: usize,
autospace_style: InlineStyle,
letter_spacing: LayoutLength,
boundary_policy: InlineBoundaryPolicy,
line_relative_alignment: Option<InlineScopeLineRelativeAlignment>,
line_relative_style: Option<Rc<ComputedStyle>>,
}
impl InlineTrackingScope {
pub(in crate::layout) fn root(style: &ComputedStyle) -> Rc<Self> {
Rc::new(Self {
parent: None,
depth: 0,
autospace_style: inline_style(style),
letter_spacing: style.used_letter_spacing(),
boundary_policy: InlineBoundaryPolicy::from_style(style),
line_relative_alignment: None,
line_relative_style: None,
})
}
pub(in crate::layout) fn child(parent: Rc<Self>, style: &ComputedStyle) -> Rc<Self> {
let line_relative_alignment = InlineScopeLineRelativeAlignment::from_baseline_shift(
&style.vertical_align.baseline_shift,
);
Rc::new(Self {
depth: parent.depth + 1,
parent: Some(parent),
autospace_style: inline_style(style),
letter_spacing: style.used_letter_spacing(),
boundary_policy: InlineBoundaryPolicy::from_style(style),
line_relative_alignment,
line_relative_style: line_relative_alignment
.is_some()
.then(|| Rc::new(style.clone())),
})
}
pub(in crate::layout) fn letter_spacing(&self) -> LayoutLength {
self.letter_spacing
}
pub(in crate::layout) fn scaled_for_text_fit(&self, scale: f32) -> Rc<Self> {
let parent = self
.parent
.as_deref()
.map(|parent| parent.scaled_for_text_fit(scale));
let mut autospace_style = (*self.autospace_style).clone();
autospace_style.font_size *= scale;
if matches!(
autospace_style.line_height_value,
css::ComputedLineHeight::Normal | css::ComputedLineHeight::Number(_)
) {
autospace_style.line_height = autospace_style
.line_height_value
.clone()
.projected(autospace_style.font_size)
.0;
}
let line_relative_style = self.line_relative_style.as_ref().map(|style| {
let mut style = (**style).clone();
style.font_size *= scale;
if matches!(
style.line_height_value,
css::ComputedLineHeight::Normal | css::ComputedLineHeight::Number(_)
) {
style.line_height = style.line_height_value.clone().projected(style.font_size).0;
}
Rc::new(style)
});
Rc::new(Self {
parent,
depth: self.depth,
letter_spacing: autospace_style.used_letter_spacing(),
autospace_style: Rc::new(autospace_style),
boundary_policy: self.boundary_policy,
line_relative_alignment: self.line_relative_alignment,
line_relative_style,
})
}
pub(in crate::layout) fn boundary_policy(&self) -> InlineBoundaryPolicy {
self.boundary_policy
}
pub(in crate::layout) fn autospace_style(&self) -> &ComputedStyle {
&self.autospace_style
}
pub(in crate::layout) fn nearest_line_relative_scope(&self) -> Option<&InlineTrackingScope> {
let mut scope = Some(self);
while let Some(current) = scope {
if current.line_relative_alignment.is_some() {
return Some(current);
}
scope = current.parent.as_deref();
}
None
}
pub(in crate::layout) fn line_relative_alignment(
&self,
) -> Option<InlineScopeLineRelativeAlignment> {
self.line_relative_alignment
}
pub(in crate::layout) fn line_relative_style(&self) -> &ComputedStyle {
debug_assert!(self.line_relative_alignment.is_some());
self.line_relative_style
.as_deref()
.expect("a line-relative inline scope retains its own style")
}
fn lowest_common<'left>(left: &'left Self, right: &Self) -> &'left Self {
let mut left = left;
let mut right = right;
while left.depth > right.depth {
left = left
.parent
.as_deref()
.expect("a deeper inline tracking scope has a parent");
}
while right.depth > left.depth {
right = right
.parent
.as_deref()
.expect("a deeper inline tracking scope has a parent");
}
while !std::ptr::eq(left, right) {
left = left
.parent
.as_deref()
.expect("all inline tracking participants share a paragraph root");
right = right
.parent
.as_deref()
.expect("all inline tracking participants share a paragraph root");
}
left
}
pub(in crate::layout) fn common_boundary_policy(
left: &Self,
right: &Self,
) -> InlineBoundaryPolicy {
Self::lowest_common(left, right).boundary_policy()
}
pub(in crate::layout) fn common_autospace_style<'left>(
left: &'left Self,
right: &Self,
) -> &'left ComputedStyle {
Self::lowest_common(left, right).autospace_style()
}
}
pub(in crate::layout) fn inline_style(style: &ComputedStyle) -> InlineStyle {
Rc::new(style.clone())
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(in crate::layout) struct InlineVisualOffset {
pub(in crate::layout) vector: InlineVector,
}
impl InlineVisualOffset {
pub(in crate::layout) fn zero() -> Self {
Self {
vector: InlineVector::new(0.0, 0.0),
}
}
pub(in crate::layout) fn from_relative_offset(offset: RelativeOffset) -> Self {
Self {
vector: InlineVector::new(offset.x(), offset.y()),
}
}
pub(in crate::layout) fn plus(self, other: Self) -> Self {
Self {
vector: self.vector + other.vector,
}
}
pub(in crate::layout) fn is_zero(self) -> bool {
self.x().abs() <= 0.01 && self.y().abs() <= 0.01
}
pub(in crate::layout) fn x(self) -> f32 {
self.vector.x
}
pub(in crate::layout) fn y(self) -> f32 {
self.vector.y
}
}
impl Default for InlineVisualOffset {
fn default() -> Self {
Self::zero()
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(in crate::layout) enum FirstLetterPseudoFragmentRole {
#[default]
Ordinary,
AssociatedPrefix,
TypographicInitial,
AssociatedSuffix,
LeadingPreservedWhitespace,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(in crate::layout) struct FirstLetterPseudoGroupId(u64);
impl FirstLetterPseudoGroupId {
pub(in crate::layout) fn allocate() -> Self {
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
Self(NEXT_ID.fetch_add(1, Ordering::Relaxed))
}
}
#[derive(Debug, Clone)]
pub(in crate::layout) struct InlineFragmentData {
pub(in crate::layout) text: Rc<str>,
pub(in crate::layout) source_run: Rc<()>,
pub(in crate::layout) style: Rc<ComputedStyle>,
pub(in crate::layout) link_target: Option<Rc<str>>,
pub(in crate::layout) mergeable: bool,
pub(in crate::layout) source: InlineTextSource,
pub(in crate::layout) generated_leader: bool,
pub(in crate::layout) force_inline_background_paint: bool,
pub(in crate::layout) hanging_edges: InlineHangingEdges,
pub(in crate::layout) source_shaped_selection: Option<SourceShapedSelection>,
pub(in crate::layout) boundary_shaped_source: Option<Rc<BoundaryShapedSource>>,
pub(in crate::layout) boundary_shaped_range: Option<std::ops::Range<usize>>,
pub(in crate::layout) resolved_bidi_direction: Option<ResolvedBidiDirection>,
pub(in crate::layout) excluded_positioning_geometry_source:
Option<InlinePositioningContainingBlockId>,
pub(in crate::layout) ancestor_inline_decorations: Rc<[InlineAncestorDecoration]>,
pub(in crate::layout) tracking_scope: Option<Rc<InlineTrackingScope>>,
pub(in crate::layout) starts_visual_fragment: bool,
pub(in crate::layout) selected_discretionary_marker: bool,
pub(in crate::layout) first_letter_pseudo_role: FirstLetterPseudoFragmentRole,
pub(in crate::layout) first_letter_pseudo_group_id: Option<FirstLetterPseudoGroupId>,
pub(in crate::layout) out_of_flow_paint_inline_advance: Option<LayoutLength>,
pub(in crate::layout) out_of_flow_paint_block_size: Option<LayoutLength>,
}
#[derive(Debug, Clone)]
pub(in crate::layout) struct BoundaryShapedSource {
pub(in crate::layout) shaped: Rc<ShapedInlineLine>,
}
#[derive(Debug, Clone)]
pub(in crate::layout) struct SourceShapedSelection {
source: Rc<ShapedInlineLine>,
source_range: std::ops::Range<usize>,
selected: Rc<ShapedInlineLine>,
visual_text: Rc<str>,
resolved_bidi_direction: Option<ResolvedBidiDirection>,
}
impl SourceShapedSelection {
pub(in crate::layout) fn from_source(
source: Rc<ShapedInlineLine>,
source_range: std::ops::Range<usize>,
) -> Option<Self> {
let selected = Rc::new(source.source_slice(source_range.clone())?);
Some(Self {
source,
source_range,
visual_text: Rc::clone(&selected.text),
selected,
resolved_bidi_direction: None,
})
}
pub(in crate::layout) fn subselection(&self, range: std::ops::Range<usize>) -> Option<Self> {
let source_range =
(self.source_range.start + range.start)..(self.source_range.start + range.end);
if range.end > self.selected.text.len()
|| self.selected.text.get(range) != self.source.text.get(source_range.clone())
{
return None;
}
Self::from_source(Rc::clone(&self.source), source_range)
}
pub(in crate::layout) fn selected(&self) -> &ShapedInlineLine {
&self.selected
}
pub(in crate::layout) fn selected_rc(&self) -> Rc<ShapedInlineLine> {
Rc::clone(&self.selected)
}
pub(in crate::layout) fn selected_mut(&mut self) -> &mut ShapedInlineLine {
Rc::make_mut(&mut self.selected)
}
pub(in crate::layout) fn replace_selected(&mut self, selected: ShapedInlineLine) {
debug_assert_eq!(selected.text, self.selected.text);
self.selected = Rc::new(selected);
}
pub(in crate::layout) fn resolve_bidi_context(
&mut self,
direction: ResolvedBidiDirection,
visual_text: impl Into<Rc<str>>,
) {
self.resolved_bidi_direction = Some(direction);
self.visual_text = visual_text.into();
}
pub(in crate::layout) fn is_reusable_for(
&self,
text: &str,
direction: Option<ResolvedBidiDirection>,
) -> bool {
self.visual_text.as_ref() == text
&& self.source.text.get(self.source_range.clone()) == Some(self.selected.text.as_ref())
&& self.resolved_bidi_direction == direction
}
pub(in crate::layout) fn combine_contiguous(
selections: &[&SourceShapedSelection],
) -> Option<ShapedInlineLine> {
let first = *selections.first()?;
if !selections.iter().all(|selection| {
Rc::ptr_eq(&first.source, &selection.source)
&& first.resolved_bidi_direction == selection.resolved_bidi_direction
}) {
return None;
}
let mut ranges = selections
.iter()
.map(|selection| selection.source_range.clone())
.collect::<Vec<_>>();
ranges.sort_by_key(|range| range.start);
let range = ranges
.iter()
.skip(1)
.try_fold(ranges.first()?.clone(), |range, next| {
(range.end == next.start).then_some(range.start..next.end)
})?;
first.source.source_slice(range)
}
}
#[derive(Debug, Clone)]
pub(in crate::layout) struct InlineFragment {
pub(in crate::layout) data: Rc<InlineFragmentData>,
pub(in crate::layout) baseline_shift: f32,
pub(in crate::layout) visual_offset: InlineVisualOffset,
}
impl InlineFragment {
#[allow(clippy::too_many_arguments)]
pub(in crate::layout) fn new(
text: impl Into<String>,
style: ComputedStyle,
baseline_shift: f32,
link_target: Option<String>,
mergeable: bool,
source: InlineTextSource,
generated_leader: bool,
hanging_edges: InlineHangingEdges,
ancestor_inline_decorations: Vec<InlineAncestorDecoration>,
) -> Self {
Self::new_shared_style(
Rc::<str>::from(text.into()),
Rc::new(style),
baseline_shift,
link_target.map(Rc::from),
mergeable,
source,
generated_leader,
hanging_edges,
Rc::from(ancestor_inline_decorations.into_boxed_slice()),
)
}
#[allow(clippy::too_many_arguments)]
pub(in crate::layout) fn new_shared_style(
text: impl Into<Rc<str>>,
style: InlineStyle,
baseline_shift: f32,
link_target: Option<Rc<str>>,
mergeable: bool,
source: InlineTextSource,
generated_leader: bool,
hanging_edges: InlineHangingEdges,
ancestor_inline_decorations: Rc<[InlineAncestorDecoration]>,
) -> Self {
Self {
data: Rc::new(InlineFragmentData {
text: text.into(),
source_run: Rc::new(()),
style,
link_target,
mergeable,
source,
generated_leader,
force_inline_background_paint: false,
hanging_edges,
source_shaped_selection: None,
boundary_shaped_source: None,
boundary_shaped_range: None,
resolved_bidi_direction: None,
excluded_positioning_geometry_source: None,
ancestor_inline_decorations,
tracking_scope: None,
starts_visual_fragment: false,
selected_discretionary_marker: false,
first_letter_pseudo_role: FirstLetterPseudoFragmentRole::Ordinary,
first_letter_pseudo_group_id: None,
out_of_flow_paint_inline_advance: None,
out_of_flow_paint_block_size: None,
}),
baseline_shift,
visual_offset: InlineVisualOffset::zero(),
}
}
pub(in crate::layout) fn with_baseline_shift(mut self, baseline_shift: f32) -> Self {
self.baseline_shift = baseline_shift;
self
}
pub(in crate::layout) fn with_excluded_positioning_geometry_source(
mut self,
source: Option<InlinePositioningContainingBlockId>,
) -> Self {
Rc::make_mut(&mut self.data).excluded_positioning_geometry_source = source;
self
}
pub(in crate::layout) fn excluded_positioning_geometry_source(
&self,
) -> Option<InlinePositioningContainingBlockId> {
self.data.excluded_positioning_geometry_source
}
pub(in crate::layout) fn with_visual_offset(
mut self,
visual_offset: InlineVisualOffset,
) -> Self {
self.visual_offset = visual_offset;
self
}
pub(in crate::layout) fn with_tracking_scope(mut self, scope: Rc<InlineTrackingScope>) -> Self {
Rc::make_mut(&mut self.data).tracking_scope = Some(scope);
self
}
pub(in crate::layout) fn with_source_run(mut self, source_run: Rc<()>) -> Self {
Rc::make_mut(&mut self.data).source_run = source_run;
self
}
pub(in crate::layout) fn source_run(&self) -> &Rc<()> {
&self.data.source_run
}
pub(in crate::layout) fn tracking_scope(&self) -> Option<&Rc<InlineTrackingScope>> {
self.data.tracking_scope.as_ref()
}
pub(in crate::layout) fn line_relative_scope(&self) -> Option<&InlineTrackingScope> {
self.tracking_scope()
.and_then(|scope| scope.nearest_line_relative_scope())
}
pub(in crate::layout) fn line_relative_alignment(
&self,
) -> Option<InlineScopeLineRelativeAlignment> {
self.line_relative_scope()
.and_then(InlineTrackingScope::line_relative_alignment)
}
pub(in crate::layout) fn starts_visual_fragment(&self) -> bool {
self.data.starts_visual_fragment
}
pub(in crate::layout) fn mark_starts_visual_fragment(&mut self) {
Rc::make_mut(&mut self.data).starts_visual_fragment = true;
}
pub(in crate::layout) fn mark_selected_discretionary_marker(&mut self) {
let data = Rc::make_mut(&mut self.data);
data.selected_discretionary_marker = true;
data.mergeable = false;
}
#[cfg(test)]
pub(in crate::layout) fn is_selected_discretionary_marker(&self) -> bool {
self.data.selected_discretionary_marker
}
pub(in crate::layout) fn set_first_letter_pseudo_role(
&mut self,
role: FirstLetterPseudoFragmentRole,
) {
Rc::make_mut(&mut self.data).first_letter_pseudo_role = role;
}
pub(in crate::layout) fn first_letter_pseudo_role(&self) -> FirstLetterPseudoFragmentRole {
self.data.first_letter_pseudo_role
}
pub(in crate::layout) fn set_first_letter_pseudo_group_id(
&mut self,
group_id: FirstLetterPseudoGroupId,
) {
Rc::make_mut(&mut self.data).first_letter_pseudo_group_id = Some(group_id);
}
pub(in crate::layout) fn first_letter_pseudo_group_id(
&self,
) -> Option<FirstLetterPseudoGroupId> {
self.data.first_letter_pseudo_group_id
}
pub(in crate::layout) fn set_out_of_flow_paint_inline_advance(
&mut self,
advance: LayoutLength,
) {
Rc::make_mut(&mut self.data).out_of_flow_paint_inline_advance = Some(advance);
}
pub(in crate::layout) fn out_of_flow_paint_inline_advance(&self) -> Option<LayoutLength> {
self.data.out_of_flow_paint_inline_advance
}
pub(in crate::layout) fn set_out_of_flow_paint_block_size(&mut self, size: LayoutLength) {
Rc::make_mut(&mut self.data).out_of_flow_paint_block_size = Some(size);
}
pub(in crate::layout) fn out_of_flow_paint_block_size(&self) -> Option<LayoutLength> {
self.data.out_of_flow_paint_block_size
}
pub(in crate::layout) fn with_hanging_edges(
mut self,
hanging_edges: InlineHangingEdges,
) -> Self {
Rc::make_mut(&mut self.data).hanging_edges = hanging_edges;
self
}
pub(in crate::layout) fn set_text(&mut self, text: impl Into<Rc<str>>) {
let data = Rc::make_mut(&mut self.data);
let text = text.into();
if data.text != text {
data.source_shaped_selection = None;
data.boundary_shaped_source = None;
data.boundary_shaped_range = None;
}
data.text = text;
}
pub(in crate::layout) fn clear_cached_shaping_for_used_style_change(&mut self) {
let data = Rc::make_mut(&mut self.data);
data.source_shaped_selection = None;
data.boundary_shaped_source = None;
data.boundary_shaped_range = None;
}
pub(in crate::layout) fn set_mergeable(&mut self, mergeable: bool) {
Rc::make_mut(&mut self.data).mergeable = mergeable;
}
pub(in crate::layout) fn set_source_shaped_selection(
&mut self,
selection: Option<SourceShapedSelection>,
) {
if let Some(selection) = &selection {
debug_assert!(
selection.source.text.get(selection.source_range.clone())
== Some(self.data.text.as_ref())
);
}
Rc::make_mut(&mut self.data).source_shaped_selection = selection;
}
pub(in crate::layout) fn source_shaped_selection(&self) -> Option<&SourceShapedSelection> {
self.data.source_shaped_selection.as_ref()
}
pub(in crate::layout) fn set_boundary_shaped_source(
&mut self,
source: Rc<BoundaryShapedSource>,
range: std::ops::Range<usize>,
) {
let data = Rc::make_mut(&mut self.data);
data.boundary_shaped_source = Some(source);
data.boundary_shaped_range = Some(range);
}
pub(in crate::layout) fn boundary_shaped_source(&self) -> Option<&BoundaryShapedSource> {
self.data.boundary_shaped_source.as_deref()
}
pub(in crate::layout) fn boundary_shaped_range(&self) -> Option<&std::ops::Range<usize>> {
self.data.boundary_shaped_range.as_ref()
}
pub(in crate::layout) fn boundary_shaped_source_and_range(
&self,
) -> Option<(Rc<BoundaryShapedSource>, std::ops::Range<usize>)> {
Some((
Rc::clone(self.data.boundary_shaped_source.as_ref()?),
self.data.boundary_shaped_range.as_ref()?.clone(),
))
}
pub(in crate::layout) fn set_resolved_bidi_direction(
&mut self,
value: Option<ResolvedBidiDirection>,
) {
Rc::make_mut(&mut self.data).resolved_bidi_direction = value;
}
pub(in crate::layout) fn set_force_inline_background_paint(&mut self, value: bool) {
Rc::make_mut(&mut self.data).force_inline_background_paint = value;
}
pub(in crate::layout) fn force_inline_background_paint(&self) -> bool {
self.data.force_inline_background_paint
}
#[cfg(test)]
pub(in crate::layout) fn set_link_target(&mut self, link_target: Option<String>) {
Rc::make_mut(&mut self.data).link_target = link_target.map(Rc::from);
}
#[cfg(test)]
pub(in crate::layout) fn set_generated_leader(&mut self, generated_leader: bool) {
Rc::make_mut(&mut self.data).generated_leader = generated_leader;
}
pub(in crate::layout) fn style_mut(&mut self) -> &mut ComputedStyle {
Rc::make_mut(&mut Rc::make_mut(&mut self.data).style)
}
pub(in crate::layout) fn apply_to_ancestor_inline_decoration_styles(
&mut self,
mut apply: impl FnMut(&mut ComputedStyle),
) {
let data = Rc::make_mut(&mut self.data);
let decorations = Rc::make_mut(&mut data.ancestor_inline_decorations);
decorations
.iter_mut()
.for_each(|decoration| apply(&mut decoration.style));
}
pub(in crate::layout) fn text(&self) -> &str {
&self.data.text
}
pub(in crate::layout) fn style(&self) -> &ComputedStyle {
&self.data.style
}
pub(in crate::layout) fn link_target(&self) -> Option<&str> {
self.data.link_target.as_deref()
}
pub(in crate::layout) fn mergeable(&self) -> bool {
self.data.mergeable
}
pub(in crate::layout) fn source(&self) -> InlineTextSource {
self.data.source
}
pub(in crate::layout) fn generated_leader(&self) -> bool {
self.data.generated_leader
}
pub(in crate::layout) fn hanging_edges(&self) -> InlineHangingEdges {
self.data.hanging_edges
}
pub(in crate::layout) fn ancestor_inline_decorations(&self) -> &[InlineAncestorDecoration] {
&self.data.ancestor_inline_decorations
}
pub(in crate::layout) fn push_ancestor_inline_decoration(
&mut self,
decoration: InlineAncestorDecoration,
) {
let data = Rc::make_mut(&mut self.data);
let mut decorations = data.ancestor_inline_decorations.to_vec();
decorations.push(decoration);
data.ancestor_inline_decorations = Rc::from(decorations.into_boxed_slice());
}
}
pub(in crate::layout) trait InlineFragmentAccess {
fn text(&self) -> &str;
fn style(&self) -> &ComputedStyle;
fn baseline_shift(&self) -> f32;
fn visual_offset(&self) -> InlineVisualOffset;
fn link_target(&self) -> Option<&str>;
fn mergeable(&self) -> bool;
fn source(&self) -> InlineTextSource;
fn source_run(&self) -> &Rc<()>;
fn tracking_scope(&self) -> Option<&Rc<InlineTrackingScope>>;
fn generated_leader(&self) -> bool;
fn first_letter_pseudo_group_id(&self) -> Option<FirstLetterPseudoGroupId> {
None
}
fn boundary_shaped_source(&self) -> Option<&BoundaryShapedSource> {
None
}
fn boundary_shaped_range(&self) -> Option<&std::ops::Range<usize>> {
None
}
fn source_shaped_selection(&self) -> Option<&SourceShapedSelection> {
None
}
fn resolved_bidi_direction(&self) -> Option<ResolvedBidiDirection>;
fn ancestor_inline_decorations(&self) -> &[InlineAncestorDecoration];
}
impl InlineFragmentAccess for InlineFragment {
fn text(&self) -> &str {
self.text()
}
fn style(&self) -> &ComputedStyle {
self.style()
}
fn baseline_shift(&self) -> f32 {
self.baseline_shift
}
fn visual_offset(&self) -> InlineVisualOffset {
self.visual_offset
}
fn link_target(&self) -> Option<&str> {
self.link_target()
}
fn mergeable(&self) -> bool {
self.mergeable()
}
fn source(&self) -> InlineTextSource {
self.source()
}
fn source_run(&self) -> &Rc<()> {
InlineFragment::source_run(self)
}
fn tracking_scope(&self) -> Option<&Rc<InlineTrackingScope>> {
InlineFragment::tracking_scope(self)
}
fn generated_leader(&self) -> bool {
self.generated_leader()
}
fn first_letter_pseudo_group_id(&self) -> Option<FirstLetterPseudoGroupId> {
InlineFragment::first_letter_pseudo_group_id(self)
}
fn boundary_shaped_source(&self) -> Option<&BoundaryShapedSource> {
InlineFragment::boundary_shaped_source(self)
}
fn boundary_shaped_range(&self) -> Option<&std::ops::Range<usize>> {
InlineFragment::boundary_shaped_range(self)
}
fn source_shaped_selection(&self) -> Option<&SourceShapedSelection> {
InlineFragment::source_shaped_selection(self)
}
fn resolved_bidi_direction(&self) -> Option<ResolvedBidiDirection> {
self.data.resolved_bidi_direction
}
fn ancestor_inline_decorations(&self) -> &[InlineAncestorDecoration] {
self.ancestor_inline_decorations()
}
}
#[derive(Debug, Clone, Copy)]
pub(in crate::layout) struct PendingInlineFragment<'a> {
fragment: &'a InlineFragment,
baseline_shift: f32,
visual_offset: InlineVisualOffset,
}
impl<'a> PendingInlineFragment<'a> {
pub(in crate::layout) fn new(fragment: &'a InlineFragment) -> Self {
Self {
fragment,
baseline_shift: fragment.baseline_shift,
visual_offset: fragment.visual_offset,
}
}
pub(in crate::layout) fn to_owned_fragment(self) -> InlineFragment {
self.fragment
.clone()
.with_baseline_shift(self.baseline_shift())
.with_visual_offset(self.visual_offset())
}
pub(in crate::layout) fn line_relative_alignment(
self,
) -> Option<InlineScopeLineRelativeAlignment> {
self.fragment.line_relative_alignment()
}
pub(in crate::layout) fn excluded_positioning_geometry_source(
self,
) -> Option<InlinePositioningContainingBlockId> {
self.fragment.excluded_positioning_geometry_source()
}
}
impl InlineFragmentAccess for PendingInlineFragment<'_> {
fn text(&self) -> &str {
self.fragment.text()
}
fn style(&self) -> &ComputedStyle {
self.fragment.style()
}
fn baseline_shift(&self) -> f32 {
self.baseline_shift
}
fn visual_offset(&self) -> InlineVisualOffset {
self.visual_offset
}
fn link_target(&self) -> Option<&str> {
self.fragment.link_target()
}
fn mergeable(&self) -> bool {
self.fragment.mergeable()
}
fn source(&self) -> InlineTextSource {
self.fragment.source()
}
fn source_run(&self) -> &Rc<()> {
self.fragment.source_run()
}
fn tracking_scope(&self) -> Option<&Rc<InlineTrackingScope>> {
self.fragment.tracking_scope()
}
fn generated_leader(&self) -> bool {
self.fragment.generated_leader()
}
fn first_letter_pseudo_group_id(&self) -> Option<FirstLetterPseudoGroupId> {
self.fragment.first_letter_pseudo_group_id()
}
fn boundary_shaped_source(&self) -> Option<&BoundaryShapedSource> {
self.fragment.boundary_shaped_source()
}
fn boundary_shaped_range(&self) -> Option<&std::ops::Range<usize>> {
self.fragment.boundary_shaped_range()
}
fn source_shaped_selection(&self) -> Option<&SourceShapedSelection> {
self.fragment.source_shaped_selection()
}
fn resolved_bidi_direction(&self) -> Option<ResolvedBidiDirection> {
self.fragment.data.resolved_bidi_direction
}
fn ancestor_inline_decorations(&self) -> &[InlineAncestorDecoration] {
self.fragment.ancestor_inline_decorations()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) enum InlineTextSource {
Normal,
Generated,
GeneratedWbr,
WordSpaceTransform(ExplicitWordSeparatorSource),
BlockEllipsis,
FootnoteCall(ElementId),
RunIn,
Marker,
BidiControl,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) enum ExplicitWordSeparatorSource {
AuthoredZeroWidthSpace,
HtmlWbr,
}
impl ExplicitWordSeparatorSource {
pub(in crate::layout) const fn extraction_text(self) -> Option<&'static str> {
match self {
Self::AuthoredZeroWidthSpace => Some("\u{200b}"),
Self::HtmlWbr => None,
}
}
}
impl InlineTextSource {
pub(in crate::layout) fn is_generated(self) -> bool {
matches!(
self,
Self::Generated | Self::GeneratedWbr | Self::BlockEllipsis | Self::FootnoteCall(_)
)
}
pub(in crate::layout) fn footnote_call(self) -> Option<ElementId> {
match self {
Self::FootnoteCall(element) => Some(element),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(in crate::layout) struct InlineHangingEdges {
pub(in crate::layout) blocks_start: bool,
pub(in crate::layout) blocks_end: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) struct InlineAncestorDecoration {
pub(in crate::layout) style: ComputedStyle,
pub(in crate::layout) hanging_edges: InlineHangingEdges,
pub(in crate::layout) paints_background_or_border: bool,
pub(in crate::layout) positioning_containing_block_id:
Option<InlinePositioningContainingBlockId>,
pub(in crate::layout) paint_effect_scope_id: Option<InlinePaintScopeId>,
}
pub(in crate::layout) fn inline_style_establishes_positioned_stacking_context(
style: &ComputedStyle,
) -> bool {
matches!(style.position, Position::Relative | Position::Sticky)
&& style.z_index.establishes_stacking_context()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(in crate::layout) struct InlinePaintScopeId(u64);
impl InlinePaintScopeId {
pub(in crate::layout) fn allocate() -> Self {
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
Self(NEXT_ID.fetch_add(1, Ordering::Relaxed))
}
}
pub(in crate::layout) fn inline_ancestor_decorations_have_same_text_paint_effect(
left: &[InlineAncestorDecoration],
right: &[InlineAncestorDecoration],
) -> bool {
left.iter()
.filter_map(|decoration| decoration.paint_effect_scope_id)
.eq(right
.iter()
.filter_map(|decoration| decoration.paint_effect_scope_id))
&& left
.iter()
.filter(|decoration| {
inline_style_establishes_positioned_stacking_context(&decoration.style)
})
.map(|decoration| decoration.positioning_containing_block_id)
.eq(right
.iter()
.filter(|decoration| {
inline_style_establishes_positioned_stacking_context(&decoration.style)
})
.map(|decoration| decoration.positioning_containing_block_id))
}
#[derive(Debug, Clone, Copy)]
pub(in crate::layout) struct StaticPositionCapture {
pub(in crate::layout) rectangle: StaticPositionRectangle,
}
#[derive(Debug, Clone, Copy)]
pub(in crate::layout) struct PhysicalStaticAxisFallback {
pub(in crate::layout) left: f32,
pub(in crate::layout) right: f32,
pub(in crate::layout) can_fall_outside: bool,
}
impl PhysicalStaticAxisFallback {
pub(in crate::layout) fn new(left: f32, right: f32) -> Self {
Self {
left,
right,
can_fall_outside: false,
}
}
pub(in crate::layout) fn new_unclamped(left: f32, right: f32) -> Self {
Self {
left,
right,
can_fall_outside: true,
}
}
}
#[derive(Debug, Clone, Copy)]
pub(in crate::layout) struct AbsoluteStaticPosition {
page_left_x: f32,
page_right_x: f32,
page_top_y: f32,
horizontal_can_fall_outside: bool,
has_vertical_position: bool,
static_alignment_source: Option<StaticAlignmentSource>,
}
#[derive(Debug, Clone, Copy)]
pub(in crate::layout) struct StaticPositionContainingBlock {
pub(in crate::layout) axes: WritingModeAxes,
pub(in crate::layout) content_rect: PageTopRect,
pub(in crate::layout) justify_items: css::SelfAlignment,
}
impl StaticPositionContainingBlock {
pub(in crate::layout) fn new(
axes: WritingModeAxes,
content_rect: PageTopRect,
justify_items: css::SelfAlignment,
) -> Self {
Self {
axes,
content_rect,
justify_items,
}
}
pub(in crate::layout) fn rectangle_at_hypothetical_block_box(
self,
hypothetical_border_box: PageTopRect,
) -> StaticPositionRectangle {
let block_start = match self.axes.physical_side(LogicalSide::BlockStart) {
PhysicalSide::Left => hypothetical_border_box.x(),
PhysicalSide::Right => hypothetical_border_box.x() + hypothetical_border_box.width(),
PhysicalSide::Top => hypothetical_border_box.top_y(),
PhysicalSide::Bottom => {
hypothetical_border_box.top_y() + hypothetical_border_box.height()
}
};
let area = match self.axes.physical_axis(LogicalAxis::Inline) {
PhysicalAxis::Horizontal => PageTopRect::new(
self.content_rect.x(),
block_start,
self.content_rect.width(),
0.0,
),
PhysicalAxis::Vertical => PageTopRect::new(
block_start,
self.content_rect.top_y(),
0.0,
self.content_rect.height(),
),
};
StaticPositionRectangle {
area,
writing_mode: self.axes.writing_mode(),
direction: self.axes.direction(),
justify_items: self.justify_items,
align_items: css::SelfAlignment::NORMAL,
}
}
}
#[derive(Debug, Clone, Copy)]
pub(in crate::layout) struct StaticPositionRectangle {
pub(in crate::layout) area: PageTopRect,
pub(in crate::layout) writing_mode: WritingMode,
pub(in crate::layout) direction: Direction,
pub(in crate::layout) justify_items: css::SelfAlignment,
pub(in crate::layout) align_items: css::SelfAlignment,
}
impl StaticPositionRectangle {
pub(in crate::layout) fn css2_horizontal_direction(self) -> Direction {
crate::layout::assets::physical_horizontal_axis_direction(self.writing_mode, self.direction)
}
}
#[derive(Debug, Clone, Copy)]
enum StaticAlignmentSource {
OrdinaryFlow {
rectangle: StaticPositionRectangle,
alignment: Option<AbsposStaticAlignment>,
},
FormattingContext(AbsposStaticAlignment),
}
#[derive(Debug, Clone, Copy)]
pub(in crate::layout) struct AbsposStaticAlignment {
pub(in crate::layout) area: PageTopRect,
pub(in crate::layout) writing_mode: WritingMode,
pub(in crate::layout) direction: Direction,
pub(in crate::layout) subject_writing_mode: WritingMode,
pub(in crate::layout) subject_direction: Direction,
pub(in crate::layout) inline: css::SelfAlignment,
pub(in crate::layout) block: css::SelfAlignment,
}
impl AbsposStaticAlignment {
pub(in crate::layout) fn new(
area: PageTopRect,
writing_mode: WritingMode,
direction: Direction,
subject_writing_mode: WritingMode,
subject_direction: Direction,
inline: css::SelfAlignment,
block: css::SelfAlignment,
) -> Self {
Self {
area,
writing_mode,
direction,
subject_writing_mode,
subject_direction,
inline,
block,
}
}
fn alignment_for_physical_axis(self, axis: PhysicalAxis) -> css::SelfAlignment {
let axes = WritingModeAxes::new(self.writing_mode, self.direction);
if axes.logical_axis_for_physical(axis) == LogicalAxis::Inline {
self.inline
} else {
self.block
}
}
fn alignment_direction(self, axis: PhysicalAxis) -> AbsposAlignmentDirection {
let container_axes = WritingModeAxes::new(self.writing_mode, self.direction);
let container_logical_axis = container_axes.logical_axis_for_physical(axis);
let subject_axes = WritingModeAxes::new(self.subject_writing_mode, self.subject_direction);
let subject_logical_axis = subject_axes.logical_axis_for_physical(axis);
let container_reverse_start_end = matches!(
container_axes.physical_start_side(container_logical_axis),
PhysicalSide::Right | PhysicalSide::Bottom
);
let subject_reverse_start_end = matches!(
subject_axes.physical_start_side(subject_logical_axis),
PhysicalSide::Right | PhysicalSide::Bottom
);
AbsposAlignmentDirection {
container_reverse_start_end,
subject_reverse_start_end,
left_right_are_physical: axis == PhysicalAxis::Horizontal
&& container_logical_axis == LogicalAxis::Inline,
left_right_resolve_to_inline_edges: container_logical_axis == LogicalAxis::Inline,
}
}
pub(in crate::layout) fn available_outer_size(
self,
axis: PhysicalAxis,
containing_block: ContainingBlock,
) -> Option<f32> {
let alignment = self.alignment_for_physical_axis(axis);
let direction = self.alignment_direction(axis);
let (area_start, area_size, containing_start, containing_size) = match axis {
PhysicalAxis::Horizontal => (
self.area.x(),
self.area.width(),
containing_block.x(),
containing_block.width(),
),
PhysicalAxis::Vertical => (
self.area.top_y(),
self.area.height(),
containing_block.top_y(),
containing_block.height(),
),
};
match alignment.keyword {
SelfAlignmentKeyword::Center => Some({
let center = area_start + area_size / 2.0;
(2.0 * (center - containing_start).min(containing_start + containing_size - center))
.max(0.0)
}),
keyword => {
let physical_start_is_left = match keyword {
SelfAlignmentKeyword::SelfStart | SelfAlignmentKeyword::SelfEnd => {
let subject_start_is_left = !direction.subject_reverse_start_end;
if matches!(keyword, SelfAlignmentKeyword::SelfStart) {
subject_start_is_left
} else {
!subject_start_is_left
}
}
SelfAlignmentKeyword::End | SelfAlignmentKeyword::FlexEnd => {
direction.container_reverse_start_end
}
SelfAlignmentKeyword::Right if direction.left_right_are_physical => false,
SelfAlignmentKeyword::Left if direction.left_right_are_physical => true,
_ => !direction.container_reverse_start_end,
};
let static_edge = if physical_start_is_left {
area_start
} else {
area_start + area_size
};
let containing_opposite_edge = if physical_start_is_left {
containing_start + containing_size
} else {
containing_start
};
Some((containing_opposite_edge - static_edge).abs().max(0.0))
}
}
}
pub(in crate::layout) fn available_horizontal_outer_size(
self,
containing_block: ContainingBlock,
) -> Option<f32> {
self.available_outer_size(PhysicalAxis::Horizontal, containing_block)
}
pub(in crate::layout) fn horizontal_static_position(
self,
containing_block: ContainingBlock,
border_box_width: f32,
margin_left: f32,
margin_right: f32,
) -> PhysicalStaticAxisFallback {
let outer_width = margin_left + border_box_width + margin_right;
let alignment = self.alignment_for_physical_axis(PhysicalAxis::Horizontal);
let direction = self.alignment_direction(PhysicalAxis::Horizontal);
let offset = abspos_static_alignment_offset(
alignment,
self.area.width(),
border_box_width,
margin_left,
margin_right,
direction,
);
let margin_box_offset = offset - margin_left;
let candidate_margin_box_start = self.area.x() + margin_box_offset;
let candidate_overflows_containing_block = candidate_margin_box_start
< containing_block.x()
|| candidate_margin_box_start + outer_width
> containing_block.x() + containing_block.width();
let margin_box_start = if safe_alignment_falls_back_to_static_position_start(
alignment,
offset,
self.area.width(),
border_box_width,
margin_left,
margin_right,
direction,
candidate_overflows_containing_block,
) {
if direction.container_reverse_start_end {
self.area.x() + self.area.width() - outer_width
} else {
self.area.x()
}
} else {
candidate_margin_box_start
};
let start_in_containing_block = margin_box_start - containing_block.x();
PhysicalStaticAxisFallback::new_unclamped(
start_in_containing_block,
containing_block.width() - start_in_containing_block - outer_width,
)
}
pub(in crate::layout) fn vertical_static_start(
self,
containing_block: ContainingBlock,
border_box_height: f32,
margin_top: f32,
margin_bottom: f32,
) -> f32 {
let outer_height = margin_top + border_box_height + margin_bottom;
let alignment = self.alignment_for_physical_axis(PhysicalAxis::Vertical);
let direction = self.alignment_direction(PhysicalAxis::Vertical);
let offset = abspos_static_alignment_offset(
alignment,
self.area.height(),
border_box_height,
margin_top,
margin_bottom,
direction,
);
let margin_box_offset = offset - margin_top;
let candidate_margin_box_top = self.area.top_y() - margin_box_offset;
let candidate_overflows_containing_block = candidate_margin_box_top
> containing_block.top_y()
|| candidate_margin_box_top - outer_height
< containing_block.top_y() - containing_block.height();
if safe_alignment_falls_back_to_static_position_start(
alignment,
offset,
self.area.height(),
border_box_height,
margin_top,
margin_bottom,
direction,
candidate_overflows_containing_block,
) {
let margin_box_top = if direction.container_reverse_start_end {
self.area.top_y() - outer_height
} else {
self.area.top_y()
};
containing_block.top_y() - margin_box_top
} else {
containing_block.top_y() - candidate_margin_box_top
}
}
}
#[derive(Debug, Clone, Copy)]
struct AbsposAlignmentDirection {
container_reverse_start_end: bool,
subject_reverse_start_end: bool,
left_right_are_physical: bool,
left_right_resolve_to_inline_edges: bool,
}
fn abspos_static_alignment_offset(
alignment: css::SelfAlignment,
area_size: f32,
border_size: f32,
margin_start: f32,
margin_end: f32,
direction: AbsposAlignmentDirection,
) -> f32 {
let free_space = area_size - margin_start - border_size - margin_end;
let keyword = alignment.keyword;
let start = margin_start;
let end = margin_start + free_space;
match keyword {
SelfAlignmentKeyword::Center => margin_start + free_space / 2.0,
SelfAlignmentKeyword::End | SelfAlignmentKeyword::FlexEnd => {
if direction.container_reverse_start_end {
start
} else {
end
}
}
SelfAlignmentKeyword::SelfEnd => {
if direction.subject_reverse_start_end {
start
} else {
end
}
}
SelfAlignmentKeyword::LastBaseline => {
if direction.container_reverse_start_end {
start
} else {
end
}
}
SelfAlignmentKeyword::Start | SelfAlignmentKeyword::FlexStart => {
if direction.container_reverse_start_end {
end
} else {
start
}
}
SelfAlignmentKeyword::SelfStart => {
if direction.subject_reverse_start_end {
end
} else {
start
}
}
SelfAlignmentKeyword::Left if direction.left_right_are_physical => start,
SelfAlignmentKeyword::Right if direction.left_right_are_physical => end,
SelfAlignmentKeyword::Left if direction.left_right_resolve_to_inline_edges => {
if direction.container_reverse_start_end {
end
} else {
start
}
}
SelfAlignmentKeyword::Right if direction.left_right_resolve_to_inline_edges => {
if direction.container_reverse_start_end {
start
} else {
end
}
}
SelfAlignmentKeyword::Left
| SelfAlignmentKeyword::Right
| SelfAlignmentKeyword::Auto
| SelfAlignmentKeyword::Normal
| SelfAlignmentKeyword::Stretch
| SelfAlignmentKeyword::Baseline => {
if direction.container_reverse_start_end {
end
} else {
start
}
}
}
}
#[allow(clippy::too_many_arguments)]
fn safe_alignment_falls_back_to_static_position_start(
alignment: css::SelfAlignment,
offset: f32,
area_size: f32,
border_size: f32,
margin_start: f32,
margin_end: f32,
direction: AbsposAlignmentDirection,
candidate_overflows_containing_block: bool,
) -> bool {
if alignment.safety != AlignmentSafety::Safe || !candidate_overflows_containing_block {
return false;
}
let logical_start_offset = if direction.container_reverse_start_end {
area_size - border_size - margin_end
} else {
margin_start
};
(offset - logical_start_offset).abs() > 0.01
}
impl AbsoluteStaticPosition {
pub(in crate::layout) fn from_page_rect(
page_left_x: f32,
page_right_x: f32,
page_top_y: f32,
) -> Self {
Self::from_page_rect_with_horizontal_outside(page_left_x, page_right_x, page_top_y, false)
}
pub(in crate::layout) fn from_page_rect_with_horizontal_outside(
page_left_x: f32,
page_right_x: f32,
page_top_y: f32,
horizontal_can_fall_outside: bool,
) -> Self {
Self {
page_left_x,
page_right_x,
page_top_y,
horizontal_can_fall_outside,
has_vertical_position: true,
static_alignment_source: None,
}
}
pub(in crate::layout) fn from_page_horizontal_position(
page_left_x: f32,
page_right_x: f32,
) -> Self {
Self {
page_left_x,
page_right_x,
page_top_y: 0.0,
horizontal_can_fall_outside: false,
has_vertical_position: false,
static_alignment_source: None,
}
}
pub(in crate::layout) fn with_static_alignment(
mut self,
static_alignment: AbsposStaticAlignment,
) -> Self {
self.static_alignment_source = Some(match self.static_alignment_source {
Some(StaticAlignmentSource::OrdinaryFlow { rectangle, .. }) => {
StaticAlignmentSource::OrdinaryFlow {
rectangle,
alignment: Some(static_alignment),
}
}
Some(StaticAlignmentSource::FormattingContext(_)) | None => {
StaticAlignmentSource::FormattingContext(static_alignment)
}
});
self
}
pub(in crate::layout) fn with_static_position_rectangle(
mut self,
rectangle: StaticPositionRectangle,
) -> Self {
self.static_alignment_source = Some(StaticAlignmentSource::OrdinaryFlow {
rectangle,
alignment: self
.static_alignment_source
.and_then(|source| match source {
StaticAlignmentSource::OrdinaryFlow { alignment, .. } => alignment,
StaticAlignmentSource::FormattingContext(_) => None,
}),
});
self
}
pub(in crate::layout) fn with_inline_static_position_rectangle(
mut self,
rectangle: StaticPositionRectangle,
) -> Self {
self.page_top_y = rectangle.area.top_y();
self.has_vertical_position = true;
self.with_static_position_rectangle(rectangle)
}
pub(in crate::layout) fn static_position_rectangle(self) -> Option<StaticPositionRectangle> {
match self.static_alignment_source {
Some(StaticAlignmentSource::OrdinaryFlow { rectangle, .. }) => Some(rectangle),
Some(StaticAlignmentSource::FormattingContext(_)) | None => None,
}
}
pub(in crate::layout) fn static_alignment(self) -> Option<AbsposStaticAlignment> {
match self.static_alignment_source {
Some(StaticAlignmentSource::OrdinaryFlow { alignment, .. }) => alignment,
Some(StaticAlignmentSource::FormattingContext(alignment)) => Some(alignment),
None => None,
}
}
pub(in crate::layout) fn has_formatting_context_static_alignment(self) -> bool {
matches!(
self.static_alignment_source,
Some(StaticAlignmentSource::FormattingContext(_))
)
}
pub(in crate::layout) fn horizontal_block_static_rectangle(self) -> Option<PageTopRect> {
self.has_vertical_position.then(|| {
PageTopRect::new(
self.page_left_x,
self.page_top_y,
(self.page_right_x - self.page_left_x).max(0.0),
0.0,
)
})
}
pub(in crate::layout) fn horizontal_position(
self,
containing_block: ContainingBlock,
) -> PhysicalStaticAxisFallback {
let left = self.page_left_x - containing_block.x();
let right = containing_block.x() + containing_block.width() - self.page_right_x;
if self.horizontal_can_fall_outside {
PhysicalStaticAxisFallback::new_unclamped(left, right)
} else {
PhysicalStaticAxisFallback::new(left, right)
}
}
pub(in crate::layout) fn vertical_start(self, containing_block: ContainingBlock) -> f32 {
containing_block.top_y() - self.page_top_y
}
pub(in crate::layout) const fn has_vertical_position(self) -> bool {
self.has_vertical_position
}
}
#[derive(Debug, Clone, Copy)]
pub(in crate::layout) struct InlineLineMetrics {
pub(in crate::layout) width: f32,
pub(in crate::layout) height: f32,
pub(in crate::layout) baseline_offset: f32,
}
#[derive(Debug, Clone, Copy, Default)]
pub(in crate::layout) struct HangingPunctuationWidths {
pub(in crate::layout) start: f32,
pub(in crate::layout) end: f32,
}
#[derive(Debug, Clone)]
pub(in crate::layout) struct PreparedInlineLine {
pub(in crate::layout) metrics: InlineLineMetrics,
pub(in crate::layout) paint_items: Vec<PreparedInlinePaintItem>,
pub(in crate::layout) positioning_geometry: Vec<PreparedInlinePositioningGeometry>,
pub(in crate::layout) decoration_origin_fragments:
Rc<[crate::layout::text_paint::TextDecorationOriginFragmentGeometry]>,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(in crate::layout) struct PreparedInlineLogicalContentEdges {
inline_start: InlinePositioningInlineCoordinate,
inline_end: InlinePositioningInlineCoordinate,
block_start: InlinePositioningBlockCoordinate,
block_end: InlinePositioningBlockCoordinate,
}
impl PreparedInlineLogicalContentEdges {
fn from_rect(rect: PageTopRect, axes: WritingModeAxes) -> Self {
Self {
inline_start: InlinePositioningLogicalCoordinate::from_rect_side(
rect,
axes.physical_side(LogicalSide::InlineStart),
),
inline_end: InlinePositioningLogicalCoordinate::from_rect_side(
rect,
axes.physical_side(LogicalSide::InlineEnd),
),
block_start: InlinePositioningLogicalCoordinate::from_rect_side(
rect,
axes.physical_side(LogicalSide::BlockStart),
),
block_end: InlinePositioningLogicalCoordinate::from_rect_side(
rect,
axes.physical_side(LogicalSide::BlockEnd),
),
}
}
fn extend_with_rect(&mut self, rect: PageTopRect, axes: WritingModeAxes) {
let candidate = Self::from_rect(rect, axes);
self.inline_start = self.inline_start.farther_toward(
candidate.inline_start,
axes.physical_side(LogicalSide::InlineStart),
);
self.inline_end = self.inline_end.farther_toward(
candidate.inline_end,
axes.physical_side(LogicalSide::InlineEnd),
);
self.block_start = self.block_start.farther_toward(
candidate.block_start,
axes.physical_side(LogicalSide::BlockStart),
);
self.block_end = self.block_end.farther_toward(
candidate.block_end,
axes.physical_side(LogicalSide::BlockEnd),
);
}
pub(in crate::layout) fn start_corner(self) -> InlinePositioningLogicalCorner {
InlinePositioningLogicalCorner {
inline: self.inline_start,
block: self.block_start,
}
}
pub(in crate::layout) fn end_corner(self) -> InlinePositioningLogicalCorner {
InlinePositioningLogicalCorner {
inline: self.inline_end,
block: self.block_end,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) enum InlinePositioningInlineAxis {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) enum InlinePositioningBlockAxis {}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(in crate::layout) struct InlinePositioningLogicalCoordinate<Axis> {
physical_page_coordinate: f32,
axis: std::marker::PhantomData<Axis>,
}
pub(in crate::layout) type InlinePositioningInlineCoordinate =
InlinePositioningLogicalCoordinate<InlinePositioningInlineAxis>;
pub(in crate::layout) type InlinePositioningBlockCoordinate =
InlinePositioningLogicalCoordinate<InlinePositioningBlockAxis>;
impl<Axis> InlinePositioningLogicalCoordinate<Axis> {
pub(in crate::layout) const fn new(physical_page_coordinate: f32) -> Self {
Self {
physical_page_coordinate,
axis: std::marker::PhantomData,
}
}
fn from_rect_side(rect: PageTopRect, side: PhysicalSide) -> Self {
Self::new(match side {
PhysicalSide::Left => rect.x(),
PhysicalSide::Right => rect.x() + rect.width(),
PhysicalSide::Top => rect.top_y(),
PhysicalSide::Bottom => rect.bottom_y(),
})
}
fn farther_toward(self, candidate: Self, side: PhysicalSide) -> Self {
let physical_page_coordinate = match side {
PhysicalSide::Left | PhysicalSide::Bottom => self
.physical_page_coordinate
.min(candidate.physical_page_coordinate),
PhysicalSide::Right | PhysicalSide::Top => self
.physical_page_coordinate
.max(candidate.physical_page_coordinate),
};
Self::new(physical_page_coordinate)
}
pub(in crate::layout) const fn physical_page_coordinate(self) -> f32 {
self.physical_page_coordinate
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(in crate::layout) struct InlinePositioningLogicalCorner {
pub(in crate::layout) inline: InlinePositioningInlineCoordinate,
pub(in crate::layout) block: InlinePositioningBlockCoordinate,
}
#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) struct PreparedInlinePositioningGeometry {
pub(in crate::layout) source: InlinePositioningContainingBlockId,
pub(in crate::layout) axes: WritingModeAxes,
pub(in crate::layout) content_edges: Option<PreparedInlineLogicalContentEdges>,
pub(in crate::layout) start_marker: Option<PageTopRect>,
pub(in crate::layout) end_marker: Option<PageTopRect>,
}
impl PreparedInlinePositioningGeometry {
pub(in crate::layout) fn new(
source: InlinePositioningContainingBlockId,
axes: WritingModeAxes,
) -> Self {
Self {
source,
axes,
content_edges: None,
start_marker: None,
end_marker: None,
}
}
pub(in crate::layout) fn record_content_rect(&mut self, rect: PageTopRect) {
if let Some(edges) = &mut self.content_edges {
edges.extend_with_rect(rect, self.axes);
} else {
self.content_edges = Some(PreparedInlineLogicalContentEdges::from_rect(
rect, self.axes,
));
}
}
pub(in crate::layout) fn record_marker(&mut self, edge: InlineLogicalEdge, rect: PageTopRect) {
match edge {
InlineLogicalEdge::Start => self.start_marker = Some(rect),
InlineLogicalEdge::End => self.end_marker = Some(rect),
}
}
pub(in crate::layout) fn start_corner(&self) -> Option<InlinePositioningLogicalCorner> {
self.content_edges
.map(PreparedInlineLogicalContentEdges::start_corner)
.or_else(|| {
self.start_marker.map(|marker| {
PreparedInlineLogicalContentEdges::from_rect(marker, self.axes).start_corner()
})
})
}
pub(in crate::layout) fn end_corner(&self) -> Option<InlinePositioningLogicalCorner> {
self.content_edges
.map(PreparedInlineLogicalContentEdges::end_corner)
.or_else(|| {
self.end_marker.map(|marker| {
PreparedInlineLogicalContentEdges::from_rect(marker, self.axes).end_corner()
})
})
}
}
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone)]
pub(in crate::layout) enum PreparedInlinePaintItem {
FragmentBackground(PreparedInlineFragment),
TextGroup(PreparedInlineTextGroup),
Atom(PreparedInlineAtom),
Scope(Box<PreparedInlinePaintScope>),
}
#[derive(Debug, Clone)]
pub(in crate::layout) struct PreparedInlinePaintScope {
pub(in crate::layout) kind: PreparedInlinePaintScopeKind,
pub(in crate::layout) opacity: css::Opacity,
pub(in crate::layout) items: Vec<PreparedInlinePaintItem>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) enum PreparedInlinePaintScopeKind {
FirstLine,
}
impl PreparedInlinePaintItem {
pub(in crate::layout) fn for_each_leaf<'a>(
&'a self,
visit: &mut impl FnMut(&'a PreparedInlinePaintItem),
) {
match self {
Self::Scope(scope) => {
for item in &scope.items {
item.for_each_leaf(visit);
}
}
Self::FragmentBackground(_) | Self::TextGroup(_) | Self::Atom(_) => visit(self),
}
}
fn find_map_leaf<'a, T>(
&'a self,
find: &mut impl FnMut(&'a PreparedInlinePaintItem) -> Option<T>,
) -> Option<T> {
match self {
Self::Scope(scope) => scope.items.iter().find_map(|item| item.find_map_leaf(find)),
Self::FragmentBackground(_) | Self::TextGroup(_) | Self::Atom(_) => find(self),
}
}
}
impl PreparedInlineLine {
pub(in crate::layout) fn for_each_paint_leaf<'a>(
&'a self,
mut visit: impl FnMut(&'a PreparedInlinePaintItem),
) {
for item in &self.paint_items {
item.for_each_leaf(&mut visit);
}
}
pub(in crate::layout) fn find_map_paint_leaf<'a, T>(
&'a self,
mut find: impl FnMut(&'a PreparedInlinePaintItem) -> Option<T>,
) -> Option<T> {
self.paint_items
.iter()
.find_map(|item| item.find_map_leaf(&mut find))
}
}
#[derive(Debug, Clone)]
pub(in crate::layout) struct PreparedInlineFragment {
pub(in crate::layout) fragment: InlineFragment,
pub(in crate::layout) rect: PhysicalInlineRect,
}
#[derive(Debug, Clone)]
pub(in crate::layout) struct PreparedInlineAtom {
pub(in crate::layout) atom: InlineAtom,
pub(in crate::layout) border_box: PhysicalInlineRect,
}
#[derive(Debug, Clone)]
pub(in crate::layout) struct PreparedInlineTextGroup {
pub(in crate::layout) bounds: PhysicalInlineTextBounds,
pub(in crate::layout) style: ComputedStyle,
pub(in crate::layout) line_block_size: f32,
pub(in crate::layout) decoration_provenance: Vec<PreparedTextDecorationProvenanceSegment>,
pub(in crate::layout) text_box_trim: TextBoxLineTrim,
pub(in crate::layout) paint_opacity: f32,
pub(in crate::layout) paint_scope_ancestry: Rc<[InlinePaintScopeId]>,
pub(in crate::layout) positioned_paint_style: Option<ComputedStyle>,
pub(in crate::layout) link_target: Option<String>,
pub(in crate::layout) link_paint_rect: Option<PaintRect>,
pub(in crate::layout) decoration_paint_rect: Option<PaintRect>,
pub(in crate::layout) shaped: ShapedInlineLine,
pub(in crate::layout) actual_text: Option<Rc<str>>,
pub(in crate::layout) source: InlineTextSource,
pub(in crate::layout) source_run: Rc<()>,
}
#[derive(Debug, Clone)]
pub(in crate::layout) struct PreparedTextDecorationProvenanceSegment {
pub(in crate::layout) layers: Vec<css::TextDecorationLayer>,
pub(in crate::layout) receivers: Vec<PreparedTextDecorationReceiver>,
}
#[derive(Debug, Clone)]
pub(in crate::layout) struct PreparedTextDecorationReceiver {
pub(in crate::layout) inline_span: TextInlineSpan,
pub(in crate::layout) style: ComputedStyle,
}
impl PreparedInlineTextGroup {
pub(in crate::layout) fn x(&self) -> f32 {
self.bounds.x()
}
pub(in crate::layout) fn y(&self) -> f32 {
self.bounds.y()
}
pub(in crate::layout) fn width(&self) -> f32 {
self.bounds.width()
}
pub(in crate::layout) fn set_x(&mut self, x: f32) {
self.bounds.set_x(x);
}
pub(in crate::layout) fn set_y(&mut self, y: f32) {
self.bounds.set_y(y);
}
pub(in crate::layout) fn set_width(&mut self, width: f32) {
self.bounds.set_width(width);
}
pub(in crate::layout) fn link_paint_rect(&self) -> PaintRect {
self.link_paint_rect
.unwrap_or_else(|| self.bounds.link_paint_rect(self.style.font_size))
}
}
#[derive(Debug, Clone, Copy)]
pub(in crate::layout) struct InlineLineGeometry {
pub(in crate::layout) writing_mode: WritingMode,
pub(in crate::layout) direction: Direction,
pub(in crate::layout) inline_start_offset: f32,
pub(in crate::layout) inline_start: f32,
pub(in crate::layout) inline_size: f32,
pub(in crate::layout) block_start: f32,
pub(in crate::layout) line_block_size: f32,
pub(in crate::layout) text_box_line_trim: TextBoxLineTrim,
}
#[derive(Debug, Clone, Copy)]
pub(in crate::layout) struct PhysicalInlineRect {
pub(in crate::layout) rect: InlineRect,
}
impl PhysicalInlineRect {
pub(in crate::layout) fn new(rect: InlineRect) -> Self {
Self {
rect: InlineRect::new(
rect.origin,
InlineSize::new(rect.size.width.max(0.0), rect.size.height.max(0.0)),
),
}
}
pub(in crate::layout) fn x(self) -> f32 {
self.rect.origin.x
}
pub(in crate::layout) fn y(self) -> f32 {
self.rect.origin.y
}
pub(in crate::layout) fn width(self) -> f32 {
self.rect.size.width
}
pub(in crate::layout) fn height(self) -> f32 {
self.rect.size.height
}
pub(in crate::layout) fn translated(self, offset: InlineVisualOffset) -> Self {
if offset.is_zero() {
return self;
}
Self::new(InlineRect::new(
InlinePoint::new(self.x() + offset.x(), self.y() + offset.y()),
self.rect.size,
))
}
pub(in crate::layout) fn paint_rect(self) -> PaintRect {
PaintRect::new(
PaintPoint::new(self.x(), self.y()),
PaintSize::new(self.width(), self.height()),
)
}
pub(in crate::layout) fn paint_clip(self) -> PaintClip {
PaintClip::from_paint_rect(self.paint_rect())
}
}
#[derive(Debug, Clone, Copy)]
pub(in crate::layout) struct PhysicalInlineTextBounds {
pub(in crate::layout) baseline_origin: InlinePoint,
pub(in crate::layout) inline_size: f32,
}
#[cfg(test)]
mod child_available_space_tests {
use super::*;
#[test]
fn orthogonal_fallback_is_not_a_percentage_basis() {
let space = ChildAvailableSpace::new(
WritingMode::HorizontalTb,
PhysicalContentWidth::new(content_box_pt(300.0)),
true,
None,
PhysicalContentHeight::new(content_box_pt(200.0)),
);
assert_eq!(space.available_physical_height().points(), 200.0);
assert!(!space.physical_height_percentage_basis().is_definite());
assert!(
!space
.logical_inline_percentage_basis_for(WritingMode::VerticalRl)
.is_definite()
);
assert_eq!(
space.logical_inline_percentage_basis_for(WritingMode::HorizontalTb),
PercentageBasis::definite(LogicalInlineContentSize::new(content_box_pt(300.0)))
);
}
#[test]
fn definite_perpendicular_size_projects_to_vertical_percentage_basis() {
let space = ChildAvailableSpace::new(
WritingMode::HorizontalTb,
PhysicalContentWidth::new(content_box_pt(300.0)),
true,
Some(PhysicalContentHeight::new(content_box_pt(200.0))),
PhysicalContentHeight::new(content_box_pt(500.0)),
);
assert_eq!(
space.logical_inline_percentage_basis_for(WritingMode::VerticalLr),
PercentageBasis::definite(LogicalInlineContentSize::new(content_box_pt(200.0)))
);
}
#[test]
fn auto_vertical_block_width_is_not_a_horizontal_percentage_basis() {
let space = ChildAvailableSpace::new(
WritingMode::VerticalLr,
PhysicalContentWidth::new(content_box_pt(0.0)),
false,
None,
PhysicalContentHeight::new(content_box_pt(500.0)),
);
assert!(
!space
.logical_inline_percentage_basis_for(WritingMode::HorizontalTb)
.is_definite()
);
}
#[test]
fn scrollport_availability_stays_indefinite_for_percentages() {
let space = ChildAvailableSpace::new(
WritingMode::HorizontalTb,
PhysicalContentWidth::new(content_box_pt(300.0)),
true,
None,
PhysicalContentHeight::new(content_box_pt(500.0)),
)
.with_orthogonal_available_height(
OrthogonalAvailableHeight::nearest_scroll_container(PhysicalContentHeight::new(
content_box_pt(120.0),
)),
);
assert_eq!(space.available_physical_height().points(), 120.0);
assert!(matches!(
space.orthogonal_available_height,
OrthogonalAvailableHeight::NearestScrollContainer(_)
));
assert!(
!space
.logical_inline_percentage_basis_for(WritingMode::VerticalRl)
.is_definite()
);
}
#[test]
fn abspos_static_alignment_centers_both_physical_axes() {
let alignment = AbsposStaticAlignment::new(
PageTopRect::new(10.0, 80.0, 100.0, 60.0),
WritingMode::HorizontalTb,
Direction::Ltr,
WritingMode::HorizontalTb,
Direction::Ltr,
css::SelfAlignment::new(SelfAlignmentKeyword::Center),
css::SelfAlignment::new(SelfAlignmentKeyword::Center),
);
let containing_block =
ContainingBlock::from_page_top_rect(PageTopRect::new(10.0, 80.0, 100.0, 60.0));
let horizontal = alignment.horizontal_static_position(containing_block, 20.0, 0.0, 0.0);
let vertical = alignment.vertical_static_start(containing_block, 20.0, 0.0, 0.0);
assert_eq!(horizontal.left, 40.0);
assert_eq!(horizontal.right, 40.0);
assert_eq!(vertical, 20.0);
}
#[test]
fn abspos_static_alignment_returns_horizontal_margin_box_insets() {
let containing_block =
ContainingBlock::from_page_top_rect(PageTopRect::new(10.0, 80.0, 100.0, 60.0));
let start = AbsposStaticAlignment::new(
containing_block.rect,
WritingMode::HorizontalTb,
Direction::Ltr,
WritingMode::HorizontalTb,
Direction::Ltr,
css::SelfAlignment::new(SelfAlignmentKeyword::Start),
css::SelfAlignment::NORMAL,
)
.horizontal_static_position(containing_block, 20.0, 7.0, 11.0);
assert_eq!((start.left, start.right), (0.0, 62.0));
let end = AbsposStaticAlignment::new(
containing_block.rect,
WritingMode::HorizontalTb,
Direction::Ltr,
WritingMode::HorizontalTb,
Direction::Ltr,
css::SelfAlignment::new(SelfAlignmentKeyword::End),
css::SelfAlignment::NORMAL,
)
.horizontal_static_position(containing_block, 20.0, 7.0, 11.0);
assert_eq!((end.left, end.right), (62.0, 0.0));
}
#[test]
fn abspos_static_alignment_returns_vertical_margin_box_insets() {
let containing_block =
ContainingBlock::from_page_top_rect(PageTopRect::new(10.0, 80.0, 100.0, 60.0));
let start = AbsposStaticAlignment::new(
containing_block.rect,
WritingMode::HorizontalTb,
Direction::Ltr,
WritingMode::HorizontalTb,
Direction::Ltr,
css::SelfAlignment::NORMAL,
css::SelfAlignment::new(SelfAlignmentKeyword::Start),
)
.vertical_static_start(containing_block, 20.0, 7.0, 11.0);
assert_eq!(start, 0.0);
let end = AbsposStaticAlignment::new(
containing_block.rect,
WritingMode::HorizontalTb,
Direction::Ltr,
WritingMode::HorizontalTb,
Direction::Ltr,
css::SelfAlignment::NORMAL,
css::SelfAlignment::new(SelfAlignmentKeyword::End),
)
.vertical_static_start(containing_block, 20.0, 7.0, 11.0);
assert_eq!(end, 22.0);
}
#[test]
fn abspos_static_alignment_maps_vertical_writing_inline_axis() {
let alignment = AbsposStaticAlignment::new(
PageTopRect::new(0.0, 100.0, 80.0, 120.0),
WritingMode::VerticalLr,
Direction::Ltr,
WritingMode::VerticalLr,
Direction::Ltr,
css::SelfAlignment::new(SelfAlignmentKeyword::End),
css::SelfAlignment::new(SelfAlignmentKeyword::Start),
);
let containing_block =
ContainingBlock::from_page_top_rect(PageTopRect::new(0.0, 100.0, 80.0, 120.0));
assert_eq!(
alignment.vertical_static_start(containing_block, 20.0, 0.0, 0.0),
100.0
);
}
#[test]
fn vertical_rtl_inline_static_rectangle_aligns_the_subject_bottom_to_inline_start() {
let alignment = AbsposStaticAlignment::new(
PageTopRect::new(0.0, 80.0, 20.0, 0.0),
WritingMode::VerticalLr,
Direction::Rtl,
WritingMode::VerticalLr,
Direction::Ltr,
css::SelfAlignment::NORMAL,
css::SelfAlignment::NORMAL,
);
let containing_block =
ContainingBlock::from_page_top_rect(PageTopRect::new(0.0, 200.0, 80.0, 120.0));
assert_eq!(
alignment.vertical_static_start(containing_block, 20.0, 0.0, 0.0),
100.0
);
}
#[test]
fn abspos_self_start_uses_the_subject_direction() {
let alignment = AbsposStaticAlignment::new(
PageTopRect::new(10.0, 80.0, 80.0, 0.0),
WritingMode::HorizontalTb,
Direction::Ltr,
WritingMode::HorizontalTb,
Direction::Rtl,
css::SelfAlignment::new(SelfAlignmentKeyword::SelfStart),
css::SelfAlignment::NORMAL,
);
let containing_block =
ContainingBlock::from_page_top_rect(PageTopRect::new(0.0, 100.0, 100.0, 100.0));
let position = alignment.horizontal_static_position(containing_block, 20.0, 0.0, 0.0);
assert_eq!(position.left, 70.0);
assert_eq!(position.right, 10.0);
}
#[test]
fn degenerate_inline_static_rectangle_still_centers_on_the_line() {
let alignment = AbsposStaticAlignment::new(
PageTopRect::new(40.0, 80.0, 0.0, 25.0),
WritingMode::HorizontalTb,
Direction::Ltr,
WritingMode::HorizontalTb,
Direction::Ltr,
css::SelfAlignment::NORMAL,
css::SelfAlignment::new(SelfAlignmentKeyword::Center),
);
let containing_block =
ContainingBlock::from_page_top_rect(PageTopRect::new(0.0, 100.0, 100.0, 100.0));
assert_eq!(
alignment.vertical_static_start(containing_block, 50.0, 0.0, 0.0),
7.5
);
}
#[test]
fn inline_static_rectangle_end_alignment_uses_its_line_under_edge() {
let alignment = AbsposStaticAlignment::new(
PageTopRect::new(40.0, 80.0, 0.0, 37.5),
WritingMode::HorizontalTb,
Direction::Ltr,
WritingMode::HorizontalTb,
Direction::Ltr,
css::SelfAlignment::NORMAL,
css::SelfAlignment::new(SelfAlignmentKeyword::End),
);
let containing_block =
ContainingBlock::from_page_top_rect(PageTopRect::new(0.0, 80.0, 100.0, 37.5));
assert_eq!(
alignment.vertical_static_start(containing_block, 15.0, 0.0, 0.0),
22.5
);
}
#[test]
fn static_available_size_projects_the_selected_vertical_edge() {
let alignment = AbsposStaticAlignment::new(
PageTopRect::new(10.0, 80.0, 0.0, 0.0),
WritingMode::HorizontalTb,
Direction::Ltr,
WritingMode::HorizontalTb,
Direction::Ltr,
css::SelfAlignment::NORMAL,
css::SelfAlignment::new(SelfAlignmentKeyword::End),
);
let containing_block =
ContainingBlock::from_page_top_rect(PageTopRect::new(0.0, 100.0, 100.0, 100.0));
assert_eq!(
alignment.available_outer_size(PhysicalAxis::Vertical, containing_block),
Some(20.0)
);
}
#[test]
fn escaped_atom_positioning_keeps_outer_cb_and_static_axes_separate() {
let actual_containing_block =
ContainingBlock::from_page_top_rect(PageTopRect::new(48.0, 720.0, 500.0, 700.0))
.on_page(3);
let static_position = AtomicInlineStaticPosition::new(
PageTopRect::new(0.0, 9_960.0, 120.0, 40.0),
WritingModeAxes::new(WritingMode::HorizontalTb, Direction::Ltr),
);
let context = EscapedAtomPositioningContext {
actual_containing_block,
static_position,
};
assert_eq!(context.actual_containing_block, actual_containing_block);
assert_eq!(context.actual_containing_block.origin_page_index, Some(3));
assert_eq!(
context.static_position.content_rect,
PageTopRect::new(0.0, 9_960.0, 120.0, 40.0)
);
assert_eq!(
context.static_position.axes,
WritingModeAxes::new(WritingMode::HorizontalTb, Direction::Ltr)
);
let auto_axes = EscapedAtomReplay::for_positioned_box(
context.actual_containing_block,
false,
true,
true,
)
.resolve_from_capture_origin(PaintPoint::new(0.0, 9_940.0));
assert_eq!(
auto_axes.translation_to(PaintPoint::new(160.0, 640.0)),
PaintTranslation::new(112.0, -9_300.0)
);
let explicit_axes = EscapedAtomReplay::for_positioned_box(
context.actual_containing_block,
false,
false,
false,
)
.resolve_from_capture_origin(PaintPoint::new(0.0, 9_940.0));
assert_eq!(
explicit_axes.translation_to(PaintPoint::new(160.0, 640.0)),
PaintTranslation::identity()
);
assert_eq!(auto_axes.replay_page_index(7, 3), 7);
assert_eq!(explicit_axes.replay_page_index(7, 3), 3);
let atom_local_explicit = EscapedAtomReplay::for_positioned_box(
context.actual_containing_block,
true,
false,
false,
)
.resolve_from_capture_origin(PaintPoint::new(0.0, 9_940.0));
assert_eq!(
atom_local_explicit.translation_to(PaintPoint::new(160.0, 640.0)),
PaintTranslation::new(160.0, -9_300.0)
);
assert_eq!(atom_local_explicit.replay_page_index(7, 3), 7);
let rebased = atom_local_explicit
.pending_in_enclosing_atomic_space()
.resolve_from_capture_origin(PaintPoint::new(20.0, 8_000.0));
assert_eq!(
rebased.translation_to(PaintPoint::new(200.0, 500.0)),
PaintTranslation::new(180.0, -7_500.0)
);
}
#[test]
fn escaped_atom_replay_uses_owner_specific_horizontal_sources() {
let containing_block =
ContainingBlock::from_page_top_rect(PageTopRect::new(40.0, 80.0, 50.0, 60.0));
let capture_origin = PaintPoint::new(10.0, 70.0);
let final_origin = PaintPoint::new(100.0, 20.0);
let cases = [
(false, false, PaintTranslation::identity()),
(false, true, PaintTranslation::new(60.0, 0.0)),
(true, false, PaintTranslation::new(90.0, -50.0)),
(true, true, PaintTranslation::new(90.0, -50.0)),
];
for (atom_owned, uses_static_x, expected) in cases {
let replay = EscapedAtomReplay::for_positioned_box(
containing_block,
atom_owned,
uses_static_x,
atom_owned,
)
.resolve_from_capture_origin(capture_origin);
assert_eq!(
replay.translation_to(final_origin),
expected,
"atom_owned={atom_owned}, uses_static_x={uses_static_x}",
);
}
}
#[test]
fn atomic_inline_static_position_projects_logical_axes() {
let content_rect = PageTopRect::new(7.0, 91.0, 31.0, 47.0);
for (writing_mode, direction, expected_area) in [
(
WritingMode::HorizontalTb,
Direction::Ltr,
PageTopRect::new(7.0, 91.0, 31.0, 0.0),
),
(
WritingMode::HorizontalTb,
Direction::Rtl,
PageTopRect::new(7.0, 91.0, 31.0, 0.0),
),
(
WritingMode::SidewaysRl,
Direction::Ltr,
PageTopRect::new(38.0, 91.0, 0.0, 47.0),
),
(
WritingMode::SidewaysRl,
Direction::Rtl,
PageTopRect::new(38.0, 91.0, 0.0, 47.0),
),
(
WritingMode::SidewaysLr,
Direction::Ltr,
PageTopRect::new(7.0, 91.0, 0.0, 47.0),
),
(
WritingMode::SidewaysLr,
Direction::Rtl,
PageTopRect::new(7.0, 91.0, 0.0, 47.0),
),
] {
let source = AtomicInlineStaticPosition::new(
content_rect,
WritingModeAxes::new(writing_mode, direction),
);
let rectangle = source
.in_atomic_space()
.static_position_rectangle()
.unwrap();
assert_eq!(rectangle.area, expected_area);
assert_eq!(rectangle.writing_mode, writing_mode);
assert_eq!(rectangle.direction, direction);
}
}
}
#[cfg(test)]
mod inline_paint_scope_tests {
use super::*;
fn scope_decoration(scope_id: InlinePaintScopeId) -> InlineAncestorDecoration {
let mut style = ComputedStyle::initial();
style.opacity = css::Opacity::new_clamped(0.5).expect("finite opacity");
InlineAncestorDecoration {
style,
hanging_edges: InlineHangingEdges::default(),
paints_background_or_border: false,
positioning_containing_block_id: None,
paint_effect_scope_id: Some(scope_id),
}
}
#[test]
fn equal_opacity_siblings_remain_distinct_paint_scopes() {
let left = scope_decoration(InlinePaintScopeId::allocate());
let right = scope_decoration(InlinePaintScopeId::allocate());
assert!(!inline_ancestor_decorations_have_same_text_paint_effect(
&[left],
&[right]
));
}
#[test]
fn copied_scope_identity_survives_typographic_splitting() {
let scope = InlinePaintScopeId::allocate();
let decoration = scope_decoration(scope);
let equivalent_decoration = decoration.clone();
assert!(inline_ancestor_decorations_have_same_text_paint_effect(
std::slice::from_ref(&decoration),
std::slice::from_ref(&equivalent_decoration)
));
}
}
#[cfg(test)]
mod inline_tracking_scope_tests {
use super::*;
fn scope_style() -> ComputedStyle {
ComputedStyle::initial()
}
#[test]
fn lowest_common_returns_an_identical_scope() {
let scope = InlineTrackingScope::root(&scope_style());
assert!(std::ptr::eq(
InlineTrackingScope::lowest_common(&scope, &scope),
scope.as_ref()
));
}
#[test]
fn lowest_common_returns_the_ancestor_of_a_descendant() {
let root = InlineTrackingScope::root(&scope_style());
let child = InlineTrackingScope::child(Rc::clone(&root), &scope_style());
let descendant = InlineTrackingScope::child(Rc::clone(&child), &scope_style());
assert!(std::ptr::eq(
InlineTrackingScope::lowest_common(&descendant, &child),
child.as_ref()
));
}
#[test]
fn lowest_common_returns_the_parent_of_sibling_scopes() {
let root = InlineTrackingScope::root(&scope_style());
let left = InlineTrackingScope::child(Rc::clone(&root), &scope_style());
let right = InlineTrackingScope::child(Rc::clone(&root), &scope_style());
assert!(std::ptr::eq(
InlineTrackingScope::lowest_common(&left, &right),
root.as_ref()
));
}
#[test]
fn common_autospace_style_uses_the_innermost_shared_inline_scope() {
let mut root_style = scope_style();
root_style.font_size = 17.0;
let mut child_style = root_style.clone();
child_style.font_size = 43.0;
let root = InlineTrackingScope::root(&root_style);
let left = InlineTrackingScope::child(Rc::clone(&root), &child_style);
let right = InlineTrackingScope::child(Rc::clone(&root), &child_style);
assert_eq!(
InlineTrackingScope::common_autospace_style(&left, &right).font_size,
17.0
);
assert_eq!(
InlineTrackingScope::common_autospace_style(&left, &left).font_size,
43.0
);
}
#[test]
fn lowest_common_aligns_differently_nested_cousins() {
let root = InlineTrackingScope::root(&scope_style());
let left_branch = InlineTrackingScope::child(Rc::clone(&root), &scope_style());
let left = InlineTrackingScope::child(left_branch, &scope_style());
let right_branch = InlineTrackingScope::child(Rc::clone(&root), &scope_style());
let right = InlineTrackingScope::child(
InlineTrackingScope::child(right_branch, &scope_style()),
&scope_style(),
);
assert!(std::ptr::eq(
InlineTrackingScope::lowest_common(&left, &right),
root.as_ref()
));
}
#[test]
fn descendant_scope_retains_its_local_used_letter_spacing() {
let mut tracked = scope_style();
tracked.letter_spacing = crate::css::ComputedLengthPercentage::from_points(4.0);
let root = InlineTrackingScope::root(&tracked);
let descendant = InlineTrackingScope::child(root, &scope_style());
assert_eq!(descendant.letter_spacing().points(), 0.0);
}
#[test]
fn text_fit_scope_scales_percentage_tracking_but_not_fixed_tracking() {
let mut percentage = scope_style();
percentage.font_size = 20.0;
percentage.letter_spacing = crate::css::ComputedLengthPercentage::from_percent(0.5);
let percentage_scope = InlineTrackingScope::root(&percentage);
assert_eq!(
percentage_scope
.scaled_for_text_fit(2.0)
.letter_spacing()
.points(),
20.0
);
let mut fixed = scope_style();
fixed.font_size = 20.0;
fixed.letter_spacing = crate::css::ComputedLengthPercentage::from_points(10.0);
let fixed_scope = InlineTrackingScope::root(&fixed);
assert_eq!(
fixed_scope
.scaled_for_text_fit(2.0)
.letter_spacing()
.points(),
10.0
);
}
}