Import files from Victor

fdb11f3e87
This commit is contained in:
Simon Sapin 2019-09-09 19:23:36 +02:00 committed by Anthony Ramine
parent be0e84b30f
commit 86904757e6
12 changed files with 2728 additions and 0 deletions

View file

@ -0,0 +1,625 @@
use super::*;
impl BlockFormattingContext {
pub fn construct<'a>(
context: &'a Context<'a>,
style: &'a Arc<ComputedValues>,
contents: NonReplacedContents,
) -> Self {
let (contents, contains_floats) = BlockContainer::construct(context, style, contents);
Self {
contents,
contains_floats: contains_floats == ContainsFloats::Yes,
}
}
}
enum IntermediateBlockLevelBox {
SameFormattingContextBlock {
style: Arc<ComputedValues>,
contents: IntermediateBlockContainer,
},
Independent {
style: Arc<ComputedValues>,
display_inside: DisplayInside,
contents: Contents,
},
OutOfFlowAbsolutelyPositionedBox {
style: Arc<ComputedValues>,
display_inside: DisplayInside,
contents: Contents,
},
OutOfFlowFloatBox {
style: Arc<ComputedValues>,
display_inside: DisplayInside,
contents: Contents,
},
}
/// A block container that may still have to be constructed.
///
/// Represents either the inline formatting context of an anonymous block
/// box or the yet-to-be-computed block container generated from the children
/// of a given element.
///
/// Deferring allows using rayons `into_par_iter`.
enum IntermediateBlockContainer {
InlineFormattingContext(InlineFormattingContext),
Deferred { contents: NonReplacedContents },
}
/// A builder for a block container.
///
/// This builder starts from the first child of a given DOM node
/// and does a preorder traversal of all of its inclusive siblings.
struct BlockContainerBuilder<'a> {
context: &'a Context<'a>,
block_container_style: &'a Arc<ComputedValues>,
/// The list of block-level boxes of the final block container.
///
/// Contains all the complete block level boxes we found traversing the tree
/// so far, if this is empty at the end of the traversal and the ongoing
/// inline formatting context is not empty, the block container establishes
/// an inline formatting context (see end of `build`).
///
/// DOM nodes which represent block-level boxes are immediately pushed
/// to this list with their style without ever being traversed at this
/// point, instead we just move to their next sibling. If the DOM node
/// doesn't have a next sibling, we either reached the end of the container
/// root or there are ongoing inline-level boxes
/// (see `handle_block_level_element`).
block_level_boxes: Vec<(IntermediateBlockLevelBox, BoxSlot<'a>)>,
/// The ongoing inline formatting context of the builder.
///
/// Contains all the complete inline level boxes we found traversing the
/// tree so far. If a block-level box is found during traversal,
/// this inline formatting context is pushed as a block level box to
/// the list of block-level boxes of the builder
/// (see `end_ongoing_inline_formatting_context`).
ongoing_inline_formatting_context: InlineFormattingContext,
/// The ongoing stack of inline boxes stack of the builder.
///
/// Contains all the currently ongoing inline boxes we entered so far.
/// The traversal is at all times as deep in the tree as this stack is,
/// which is why the code doesn't need to keep track of the actual
/// container root (see `handle_inline_level_element`).
///
/// Whenever the end of a DOM element that represents an inline box is
/// reached, the inline box at the top of this stack is complete and ready
/// to be pushed to the children of the next last ongoing inline box
/// the ongoing inline formatting context if the stack is now empty,
/// which means we reached the end of a child of the actual
/// container root (see `move_to_next_sibling`).
ongoing_inline_boxes_stack: Vec<InlineBox>,
/// The style of the anonymous block boxes pushed to the list of block-level
/// boxes, if any (see `end_ongoing_inline_formatting_context`).
anonymous_style: Option<Arc<ComputedValues>>,
/// Whether the resulting block container contains any float box.
contains_floats: ContainsFloats,
}
impl BlockContainer {
pub fn construct<'a>(
context: &'a Context<'a>,
block_container_style: &'a Arc<ComputedValues>,
contents: NonReplacedContents,
) -> (BlockContainer, ContainsFloats) {
let mut builder = BlockContainerBuilder {
context,
block_container_style,
block_level_boxes: Default::default(),
ongoing_inline_formatting_context: Default::default(),
ongoing_inline_boxes_stack: Default::default(),
anonymous_style: Default::default(),
contains_floats: Default::default(),
};
contents.traverse(block_container_style, context, &mut builder);
debug_assert!(builder.ongoing_inline_boxes_stack.is_empty());
if !builder
.ongoing_inline_formatting_context
.inline_level_boxes
.is_empty()
{
if builder.block_level_boxes.is_empty() {
let container = BlockContainer::InlineFormattingContext(
builder.ongoing_inline_formatting_context,
);
return (container, builder.contains_floats);
}
builder.end_ongoing_inline_formatting_context();
}
let mut contains_floats = builder.contains_floats;
let container = BlockContainer::BlockLevelBoxes(
builder
.block_level_boxes
.into_par_iter()
.mapfold_reduce_into(
&mut contains_floats,
|contains_floats, (intermediate, box_slot)| {
let (block_level_box, box_contains_floats) = intermediate.finish(context);
*contains_floats |= box_contains_floats;
box_slot.set(LayoutBox::BlockLevel(block_level_box.clone()));
block_level_box
},
|left, right| *left |= right,
)
.collect(),
);
(container, contains_floats)
}
}
impl<'a> TraversalHandler<'a> for BlockContainerBuilder<'a> {
fn handle_element(
&mut self,
style: &Arc<ComputedValues>,
display: DisplayGeneratingBox,
contents: Contents,
box_slot: BoxSlot<'a>,
) {
match display {
DisplayGeneratingBox::OutsideInside { outside, inside } => match outside {
DisplayOutside::Inline => box_slot.set(LayoutBox::InlineLevel(
self.handle_inline_level_element(style, inside, contents),
)),
DisplayOutside::Block => {
// Floats and abspos cause blockification, so they only happen in this case.
// https://drafts.csswg.org/css2/visuren.html#dis-pos-flo
if style.box_.position.is_absolutely_positioned() {
self.handle_absolutely_positioned_element(
style.clone(),
inside,
contents,
box_slot,
)
} else if style.box_.float.is_floating() {
self.handle_float_element(style.clone(), inside, contents, box_slot)
} else {
self.handle_block_level_element(style.clone(), inside, contents, box_slot)
}
}
},
}
}
fn handle_text(&mut self, input: &str, parent_style: &Arc<ComputedValues>) {
let (leading_whitespace, mut input) = self.handle_leading_whitespace(input);
if leading_whitespace || !input.is_empty() {
// This text node should be pushed either to the next ongoing
// inline level box with the parent style of that inline level box
// that will be ended, or directly to the ongoing inline formatting
// context with the parent style of that builder.
let inlines = self.current_inline_level_boxes();
fn last_text(inlines: &mut [Arc<InlineLevelBox>]) -> Option<&mut String> {
let last = inlines.last_mut()?;
if let InlineLevelBox::TextRun(_) = &**last {
// We never clone text run boxes, so the refcount is 1 and unwrap succeeds:
let last = Arc::get_mut(last).unwrap();
if let InlineLevelBox::TextRun(TextRun { text, .. }) = last {
Some(text)
} else {
unreachable!()
}
} else {
None
}
}
let mut new_text_run_contents;
let output;
if let Some(text) = last_text(inlines) {
// Append to the existing text run
new_text_run_contents = None;
output = text;
} else {
new_text_run_contents = Some(String::new());
output = new_text_run_contents.as_mut().unwrap();
}
if leading_whitespace {
output.push(' ')
}
loop {
if let Some(i) = input.bytes().position(|b| b.is_ascii_whitespace()) {
let (non_whitespace, rest) = input.split_at(i);
output.push_str(non_whitespace);
output.push(' ');
if let Some(i) = rest.bytes().position(|b| !b.is_ascii_whitespace()) {
input = &rest[i..];
} else {
break;
}
} else {
output.push_str(input);
break;
}
}
if let Some(text) = new_text_run_contents {
let parent_style = parent_style.clone();
inlines.push(Arc::new(InlineLevelBox::TextRun(TextRun {
parent_style,
text,
})))
}
}
}
}
impl<'a> BlockContainerBuilder<'a> {
/// Returns:
///
/// * Whether this text run has preserved (non-collapsible) leading whitespace
/// * The contents starting at the first non-whitespace character (or the empty string)
fn handle_leading_whitespace<'text>(&mut self, text: &'text str) -> (bool, &'text str) {
// FIXME: this is only an approximation of
// https://drafts.csswg.org/css2/text.html#white-space-model
if !text.starts_with(|c: char| c.is_ascii_whitespace()) {
return (false, text);
}
let mut inline_level_boxes = self.current_inline_level_boxes().iter().rev();
let mut stack = Vec::new();
let preserved = loop {
match inline_level_boxes.next().map(|b| &**b) {
Some(InlineLevelBox::TextRun(r)) => break !r.text.ends_with(' '),
Some(InlineLevelBox::Atomic { .. }) => break false,
Some(InlineLevelBox::OutOfFlowAbsolutelyPositionedBox(_))
| Some(InlineLevelBox::OutOfFlowFloatBox(_)) => {}
Some(InlineLevelBox::InlineBox(b)) => {
stack.push(inline_level_boxes);
inline_level_boxes = b.children.iter().rev()
}
None => {
if let Some(iter) = stack.pop() {
inline_level_boxes = iter
} else {
break false; // Paragraph start
}
}
}
};
let text = text.trim_start_matches(|c: char| c.is_ascii_whitespace());
(preserved, text)
}
fn handle_inline_level_element(
&mut self,
style: &Arc<ComputedValues>,
display_inside: DisplayInside,
contents: Contents,
) -> Arc<InlineLevelBox> {
let box_ = match contents.try_into() {
Err(replaced) => Arc::new(InlineLevelBox::Atomic {
style: style.clone(),
contents: replaced,
}),
Ok(non_replaced) => match display_inside {
DisplayInside::Flow => {
// Whatever happened before, we just found an inline level element, so
// all we need to do is to remember this ongoing inline level box.
self.ongoing_inline_boxes_stack.push(InlineBox {
style: style.clone(),
first_fragment: true,
last_fragment: false,
children: vec![],
});
NonReplacedContents::traverse(non_replaced, &style, self.context, self);
let mut inline_box = self
.ongoing_inline_boxes_stack
.pop()
.expect("no ongoing inline level box found");
inline_box.last_fragment = true;
Arc::new(InlineLevelBox::InlineBox(inline_box))
}
DisplayInside::FlowRoot => {
// a.k.a. `inline-block`
unimplemented!()
}
},
};
self.current_inline_level_boxes().push(box_.clone());
box_
}
fn handle_block_level_element(
&mut self,
style: Arc<ComputedValues>,
display_inside: DisplayInside,
contents: Contents,
box_slot: BoxSlot<'a>,
) {
// We just found a block level element, all ongoing inline level boxes
// need to be split around it. We iterate on the fragmented inline
// level box stack to take their contents and set their first_fragment
// field to false, for the fragmented inline level boxes that will
// come after the block level element.
let mut fragmented_inline_boxes =
self.ongoing_inline_boxes_stack
.iter_mut()
.rev()
.map(|ongoing| {
let fragmented = InlineBox {
style: ongoing.style.clone(),
first_fragment: ongoing.first_fragment,
// The fragmented boxes before the block level element
// are obviously not the last fragment.
last_fragment: false,
children: take(&mut ongoing.children),
};
ongoing.first_fragment = false;
fragmented
});
if let Some(last) = fragmented_inline_boxes.next() {
// There were indeed some ongoing inline level boxes before
// the block, we accumulate them as a single inline level box
// to be pushed to the ongoing inline formatting context.
let mut fragmented_inline = InlineLevelBox::InlineBox(last);
for mut fragmented_parent_inline_box in fragmented_inline_boxes {
fragmented_parent_inline_box
.children
.push(Arc::new(fragmented_inline));
fragmented_inline = InlineLevelBox::InlineBox(fragmented_parent_inline_box);
}
self.ongoing_inline_formatting_context
.inline_level_boxes
.push(Arc::new(fragmented_inline));
}
// We found a block level element, so the ongoing inline formatting
// context needs to be ended.
self.end_ongoing_inline_formatting_context();
let intermediate_box = match contents.try_into() {
Ok(contents) => match display_inside {
DisplayInside::Flow => IntermediateBlockLevelBox::SameFormattingContextBlock {
style,
contents: IntermediateBlockContainer::Deferred { contents },
},
_ => IntermediateBlockLevelBox::Independent {
style,
display_inside,
contents: contents.into(),
},
},
Err(contents) => {
let contents = Contents::Replaced(contents);
IntermediateBlockLevelBox::Independent {
style,
display_inside,
contents,
}
}
};
self.block_level_boxes.push((intermediate_box, box_slot))
}
fn handle_absolutely_positioned_element(
&mut self,
style: Arc<ComputedValues>,
display_inside: DisplayInside,
contents: Contents,
box_slot: BoxSlot<'a>,
) {
if !self.has_ongoing_inline_formatting_context() {
let box_ = IntermediateBlockLevelBox::OutOfFlowAbsolutelyPositionedBox {
style,
contents,
display_inside,
};
self.block_level_boxes.push((box_, box_slot))
} else {
let box_ = Arc::new(InlineLevelBox::OutOfFlowAbsolutelyPositionedBox(
AbsolutelyPositionedBox {
contents: IndependentFormattingContext::construct(
self.context,
&style,
display_inside,
contents,
),
style,
},
));
self.current_inline_level_boxes().push(box_.clone());
box_slot.set(LayoutBox::InlineLevel(box_))
}
}
fn handle_float_element(
&mut self,
style: Arc<ComputedValues>,
display_inside: DisplayInside,
contents: Contents,
box_slot: BoxSlot<'a>,
) {
self.contains_floats = ContainsFloats::Yes;
if !self.has_ongoing_inline_formatting_context() {
let box_ = IntermediateBlockLevelBox::OutOfFlowFloatBox {
style,
contents,
display_inside,
};
self.block_level_boxes.push((box_, box_slot));
} else {
let box_ = Arc::new(InlineLevelBox::OutOfFlowFloatBox(FloatBox {
contents: IndependentFormattingContext::construct(
self.context,
&style,
display_inside,
contents,
),
style,
}));
self.current_inline_level_boxes().push(box_.clone());
box_slot.set(LayoutBox::InlineLevel(box_))
}
}
fn end_ongoing_inline_formatting_context(&mut self) {
assert!(
self.ongoing_inline_boxes_stack.is_empty(),
"there should be no ongoing inline level boxes",
);
if self
.ongoing_inline_formatting_context
.inline_level_boxes
.is_empty()
{
// There should never be an empty inline formatting context.
return;
}
let block_container_style = self.block_container_style;
let anonymous_style = self.anonymous_style.get_or_insert_with(|| {
// If parent_style is None, the parent is the document node,
// in which case anonymous inline boxes should inherit their
// styles from initial values.
ComputedValues::anonymous_inheriting_from(Some(block_container_style))
});
let box_ = IntermediateBlockLevelBox::SameFormattingContextBlock {
style: anonymous_style.clone(),
contents: IntermediateBlockContainer::InlineFormattingContext(take(
&mut self.ongoing_inline_formatting_context,
)),
};
self.block_level_boxes.push((box_, BoxSlot::dummy()))
}
fn current_inline_level_boxes(&mut self) -> &mut Vec<Arc<InlineLevelBox>> {
match self.ongoing_inline_boxes_stack.last_mut() {
Some(last) => &mut last.children,
None => &mut self.ongoing_inline_formatting_context.inline_level_boxes,
}
}
fn has_ongoing_inline_formatting_context(&self) -> bool {
!self
.ongoing_inline_formatting_context
.inline_level_boxes
.is_empty()
|| !self.ongoing_inline_boxes_stack.is_empty()
}
}
impl IntermediateBlockLevelBox {
fn finish(self, context: &Context) -> (Arc<BlockLevelBox>, ContainsFloats) {
match self {
IntermediateBlockLevelBox::SameFormattingContextBlock { style, contents } => {
let (contents, contains_floats) = contents.finish(context, &style);
let block_level_box =
Arc::new(BlockLevelBox::SameFormattingContextBlock { contents, style });
(block_level_box, contains_floats)
}
IntermediateBlockLevelBox::Independent {
style,
display_inside,
contents,
} => {
let contents = IndependentFormattingContext::construct(
context,
&style,
display_inside,
contents,
);
(
Arc::new(BlockLevelBox::Independent { style, contents }),
ContainsFloats::No,
)
}
IntermediateBlockLevelBox::OutOfFlowAbsolutelyPositionedBox {
style,
display_inside,
contents,
} => {
let block_level_box = Arc::new(BlockLevelBox::OutOfFlowAbsolutelyPositionedBox(
AbsolutelyPositionedBox {
contents: IndependentFormattingContext::construct(
context,
&style,
display_inside,
contents,
),
style: style,
},
));
(block_level_box, ContainsFloats::No)
}
IntermediateBlockLevelBox::OutOfFlowFloatBox {
style,
display_inside,
contents,
} => {
let contents = IndependentFormattingContext::construct(
context,
&style,
display_inside,
contents,
);
let block_level_box = Arc::new(BlockLevelBox::OutOfFlowFloatBox(FloatBox {
contents,
style,
}));
(block_level_box, ContainsFloats::Yes)
}
}
}
}
impl IntermediateBlockContainer {
fn finish(
self,
context: &Context,
style: &Arc<ComputedValues>,
) -> (BlockContainer, ContainsFloats) {
match self {
IntermediateBlockContainer::Deferred { contents } => {
BlockContainer::construct(context, style, contents)
}
IntermediateBlockContainer::InlineFormattingContext(ifc) => {
// If that inline formatting context contained any float, those
// were already taken into account during the first phase of
// box construction.
(
BlockContainer::InlineFormattingContext(ifc),
ContainsFloats::No,
)
}
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::layout) enum ContainsFloats {
No,
Yes,
}
impl std::ops::BitOrAssign for ContainsFloats {
fn bitor_assign(&mut self, other: Self) {
if other == ContainsFloats::Yes {
*self = ContainsFloats::Yes;
}
}
}
impl Default for ContainsFloats {
fn default() -> Self {
ContainsFloats::No
}
}

View file

@ -0,0 +1,18 @@
use super::*;
#[derive(Debug)]
pub(in crate::layout) struct FloatBox {
pub style: Arc<ComputedValues>,
pub contents: IndependentFormattingContext,
}
/// Data kept during layout about the floats in a given block formatting context.
pub(in crate::layout) struct FloatContext {
// TODO
}
impl FloatContext {
pub fn new() -> Self {
FloatContext {}
}
}

View file

@ -0,0 +1,345 @@
use super::*;
use crate::fonts::BITSTREAM_VERA_SANS;
use crate::text::ShapedSegment;
#[derive(Debug, Default)]
pub(in crate::layout) struct InlineFormattingContext {
pub(super) inline_level_boxes: Vec<Arc<InlineLevelBox>>,
}
#[derive(Debug)]
pub(in crate::layout) enum InlineLevelBox {
InlineBox(InlineBox),
TextRun(TextRun),
OutOfFlowAbsolutelyPositionedBox(AbsolutelyPositionedBox),
OutOfFlowFloatBox(FloatBox),
Atomic {
style: Arc<ComputedValues>,
// FIXME: this should be IndependentFormattingContext:
contents: ReplacedContent,
},
}
#[derive(Debug)]
pub(in crate::layout) struct InlineBox {
pub style: Arc<ComputedValues>,
pub first_fragment: bool,
pub last_fragment: bool,
pub children: Vec<Arc<InlineLevelBox>>,
}
/// https://www.w3.org/TR/css-display-3/#css-text-run
#[derive(Debug)]
pub(in crate::layout) struct TextRun {
pub parent_style: Arc<ComputedValues>,
pub text: String,
}
struct InlineNestingLevelState<'box_tree> {
remaining_boxes: std::slice::Iter<'box_tree, Arc<InlineLevelBox>>,
fragments_so_far: Vec<Fragment>,
inline_start: Length,
max_block_size_of_fragments_so_far: Length,
}
struct PartialInlineBoxFragment<'box_tree> {
style: Arc<ComputedValues>,
start_corner: Vec2<Length>,
padding: Sides<Length>,
border: Sides<Length>,
margin: Sides<Length>,
last_box_tree_fragment: bool,
parent_nesting_level: InlineNestingLevelState<'box_tree>,
}
struct InlineFormattingContextState<'box_tree, 'cb> {
containing_block: &'cb ContainingBlock,
line_boxes: LinesBoxes,
inline_position: Length,
partial_inline_boxes_stack: Vec<PartialInlineBoxFragment<'box_tree>>,
current_nesting_level: InlineNestingLevelState<'box_tree>,
}
struct LinesBoxes {
boxes: Vec<Fragment>,
next_line_block_position: Length,
}
impl InlineFormattingContext {
pub(super) fn layout<'a>(
&'a self,
containing_block: &ContainingBlock,
tree_rank: usize,
absolutely_positioned_fragments: &mut Vec<AbsolutelyPositionedFragment<'a>>,
) -> FlowChildren {
let mut ifc = InlineFormattingContextState {
containing_block,
partial_inline_boxes_stack: Vec::new(),
line_boxes: LinesBoxes {
boxes: Vec::new(),
next_line_block_position: Length::zero(),
},
inline_position: Length::zero(),
current_nesting_level: InlineNestingLevelState {
remaining_boxes: self.inline_level_boxes.iter(),
fragments_so_far: Vec::with_capacity(self.inline_level_boxes.len()),
inline_start: Length::zero(),
max_block_size_of_fragments_so_far: Length::zero(),
},
};
loop {
if let Some(child) = ifc.current_nesting_level.remaining_boxes.next() {
match &**child {
InlineLevelBox::InlineBox(inline) => {
let partial = inline.start_layout(&mut ifc);
ifc.partial_inline_boxes_stack.push(partial)
}
InlineLevelBox::TextRun(run) => run.layout(&mut ifc),
InlineLevelBox::Atomic { style: _, contents } => {
// FIXME
match *contents {}
}
InlineLevelBox::OutOfFlowAbsolutelyPositionedBox(box_) => {
let initial_start_corner = match box_.style.specified_display {
Display::GeneratingBox(DisplayGeneratingBox::OutsideInside {
outside,
inside: _,
}) => Vec2 {
inline: match outside {
DisplayOutside::Inline => ifc.inline_position,
DisplayOutside::Block => Length::zero(),
},
block: ifc.line_boxes.next_line_block_position,
},
Display::Contents => {
panic!("display:contents does not generate an abspos box")
}
Display::None => panic!("display:none does not generate an abspos box"),
};
absolutely_positioned_fragments
.push(box_.layout(initial_start_corner, tree_rank));
}
InlineLevelBox::OutOfFlowFloatBox(_box_) => {
// TODO
continue;
}
}
} else
// Reached the end of ifc.remaining_boxes
if let Some(mut partial) = ifc.partial_inline_boxes_stack.pop() {
partial.finish_layout(
&mut ifc.current_nesting_level,
&mut ifc.inline_position,
false,
);
ifc.current_nesting_level = partial.parent_nesting_level
} else {
ifc.line_boxes
.finish_line(&mut ifc.current_nesting_level, containing_block);
return FlowChildren {
fragments: ifc.line_boxes.boxes,
block_size: ifc.line_boxes.next_line_block_position,
collapsible_margins_in_children: CollapsedBlockMargins::zero(),
};
}
}
}
}
impl LinesBoxes {
fn finish_line(
&mut self,
top_nesting_level: &mut InlineNestingLevelState,
containing_block: &ContainingBlock,
) {
let start_corner = Vec2 {
inline: Length::zero(),
block: self.next_line_block_position,
};
let size = Vec2 {
inline: containing_block.inline_size,
block: std::mem::replace(
&mut top_nesting_level.max_block_size_of_fragments_so_far,
Length::zero(),
),
};
self.next_line_block_position += size.block;
self.boxes.push(Fragment::Anonymous(AnonymousFragment {
children: take(&mut top_nesting_level.fragments_so_far),
rect: Rect { start_corner, size },
mode: containing_block.mode,
}))
}
}
impl InlineBox {
fn start_layout<'box_tree>(
&'box_tree self,
ifc: &mut InlineFormattingContextState<'box_tree, '_>,
) -> PartialInlineBoxFragment<'box_tree> {
let style = self.style.clone();
let cbis = ifc.containing_block.inline_size;
let mut padding = style.padding().percentages_relative_to(cbis);
let mut border = style.border_width().percentages_relative_to(cbis);
let mut margin = style
.margin()
.percentages_relative_to(cbis)
.auto_is(Length::zero);
if self.first_fragment {
ifc.inline_position += padding.inline_start + border.inline_start + margin.inline_start;
} else {
padding.inline_start = Length::zero();
border.inline_start = Length::zero();
margin.inline_start = Length::zero();
}
let mut start_corner = Vec2 {
block: padding.block_start + border.block_start + margin.block_start,
inline: ifc.inline_position - ifc.current_nesting_level.inline_start,
};
start_corner += &relative_adjustement(
&style,
ifc.containing_block.inline_size,
ifc.containing_block.block_size,
);
PartialInlineBoxFragment {
style,
start_corner,
padding,
border,
margin,
last_box_tree_fragment: self.last_fragment,
parent_nesting_level: std::mem::replace(
&mut ifc.current_nesting_level,
InlineNestingLevelState {
remaining_boxes: self.children.iter(),
fragments_so_far: Vec::with_capacity(self.children.len()),
inline_start: ifc.inline_position,
max_block_size_of_fragments_so_far: Length::zero(),
},
),
}
}
}
impl<'box_tree> PartialInlineBoxFragment<'box_tree> {
fn finish_layout(
&mut self,
nesting_level: &mut InlineNestingLevelState,
inline_position: &mut Length,
at_line_break: bool,
) {
let mut fragment = BoxFragment {
style: self.style.clone(),
children: take(&mut nesting_level.fragments_so_far),
content_rect: Rect {
size: Vec2 {
inline: *inline_position - self.start_corner.inline,
block: nesting_level.max_block_size_of_fragments_so_far,
},
start_corner: self.start_corner.clone(),
},
padding: self.padding.clone(),
border: self.border.clone(),
margin: self.margin.clone(),
block_margins_collapsed_with_children: CollapsedBlockMargins::zero(),
};
let last_fragment = self.last_box_tree_fragment && !at_line_break;
if last_fragment {
*inline_position += fragment.padding.inline_end
+ fragment.border.inline_end
+ fragment.margin.inline_end;
} else {
fragment.padding.inline_end = Length::zero();
fragment.border.inline_end = Length::zero();
fragment.margin.inline_end = Length::zero();
}
self.parent_nesting_level
.max_block_size_of_fragments_so_far
.max_assign(
fragment.content_rect.size.block
+ fragment.padding.block_sum()
+ fragment.border.block_sum()
+ fragment.margin.block_sum(),
);
self.parent_nesting_level
.fragments_so_far
.push(Fragment::Box(fragment));
}
}
impl TextRun {
fn layout(&self, ifc: &mut InlineFormattingContextState) {
let available = ifc.containing_block.inline_size - ifc.inline_position;
let mut chars = self.text.chars();
loop {
let mut shaped = ShapedSegment::new_with_naive_shaping(BITSTREAM_VERA_SANS.clone());
let mut last_break_opportunity = None;
loop {
let next = chars.next();
if matches!(next, Some(' ') | None) {
let inline_size = self.parent_style.font.font_size * shaped.advance_width;
if inline_size > available {
if let Some((state, iter)) = last_break_opportunity.take() {
shaped.restore(&state);
chars = iter;
}
break;
}
}
if let Some(ch) = next {
if ch == ' ' {
last_break_opportunity = Some((shaped.save(), chars.clone()))
}
shaped.append_char(ch).unwrap()
} else {
break;
}
}
let inline_size = self.parent_style.font.font_size * shaped.advance_width;
// https://www.w3.org/TR/CSS2/visudet.html#propdef-line-height
// 'normal':
// “set the used value to a "reasonable" value based on the font of the element.”
let line_height = self.parent_style.font.font_size.0 * 1.2;
let content_rect = Rect {
start_corner: Vec2 {
block: Length::zero(),
inline: ifc.inline_position - ifc.current_nesting_level.inline_start,
},
size: Vec2 {
block: line_height,
inline: inline_size,
},
};
ifc.inline_position += inline_size;
ifc.current_nesting_level
.max_block_size_of_fragments_so_far
.max_assign(line_height);
ifc.current_nesting_level
.fragments_so_far
.push(Fragment::Text(TextFragment {
parent_style: self.parent_style.clone(),
content_rect,
text: shaped,
}));
if chars.as_str().is_empty() {
break;
} else {
// New line
ifc.current_nesting_level.inline_start = Length::zero();
let mut nesting_level = &mut ifc.current_nesting_level;
for partial in ifc.partial_inline_boxes_stack.iter_mut().rev() {
partial.finish_layout(nesting_level, &mut ifc.inline_position, true);
partial.start_corner.inline = Length::zero();
partial.padding.inline_start = Length::zero();
partial.border.inline_start = Length::zero();
partial.margin.inline_start = Length::zero();
partial.parent_nesting_level.inline_start = Length::zero();
nesting_level = &mut partial.parent_nesting_level;
}
ifc.line_boxes
.finish_line(nesting_level, ifc.containing_block);
ifc.inline_position = Length::zero();
}
}
}
}

View file

@ -0,0 +1,439 @@
//! Flow layout, also known as block-and-inline layout.
use super::*;
use rayon::prelude::*;
use rayon_croissant::ParallelIteratorExt;
mod construct;
mod float;
mod inline;
mod root;
pub(super) use construct::*;
pub(super) use float::*;
pub(super) use inline::*;
#[derive(Debug)]
pub(super) struct BlockFormattingContext {
pub contents: BlockContainer,
pub contains_floats: bool,
}
#[derive(Debug)]
pub(super) enum BlockContainer {
BlockLevelBoxes(Vec<Arc<BlockLevelBox>>),
InlineFormattingContext(InlineFormattingContext),
}
#[derive(Debug)]
pub(super) enum BlockLevelBox {
SameFormattingContextBlock {
style: Arc<ComputedValues>,
contents: BlockContainer,
},
OutOfFlowAbsolutelyPositionedBox(AbsolutelyPositionedBox),
OutOfFlowFloatBox(FloatBox),
Independent {
style: Arc<ComputedValues>,
contents: IndependentFormattingContext,
},
}
pub(super) struct FlowChildren {
pub fragments: Vec<Fragment>,
pub block_size: Length,
pub collapsible_margins_in_children: CollapsedBlockMargins,
}
#[derive(Clone, Copy)]
struct CollapsibleWithParentStartMargin(bool);
impl BlockFormattingContext {
pub(super) fn layout<'a>(
&'a self,
containing_block: &ContainingBlock,
tree_rank: usize,
absolutely_positioned_fragments: &mut Vec<AbsolutelyPositionedFragment<'a>>,
) -> FlowChildren {
let mut float_context;
let float_context = if self.contains_floats {
float_context = FloatContext::new();
Some(&mut float_context)
} else {
None
};
let mut flow_children = self.contents.layout(
containing_block,
tree_rank,
absolutely_positioned_fragments,
float_context,
CollapsibleWithParentStartMargin(false),
);
flow_children.block_size += flow_children.collapsible_margins_in_children.end.solve();
flow_children
.collapsible_margins_in_children
.collapsed_through = false;
flow_children.collapsible_margins_in_children.end = CollapsedMargin::zero();
flow_children
}
}
impl BlockContainer {
fn layout<'a>(
&'a self,
containing_block: &ContainingBlock,
tree_rank: usize,
absolutely_positioned_fragments: &mut Vec<AbsolutelyPositionedFragment<'a>>,
float_context: Option<&mut FloatContext>,
collapsible_with_parent_start_margin: CollapsibleWithParentStartMargin,
) -> FlowChildren {
match self {
BlockContainer::BlockLevelBoxes(child_boxes) => layout_block_level_children(
child_boxes,
containing_block,
tree_rank,
absolutely_positioned_fragments,
float_context,
collapsible_with_parent_start_margin,
),
BlockContainer::InlineFormattingContext(ifc) => {
ifc.layout(containing_block, tree_rank, absolutely_positioned_fragments)
}
}
}
}
fn layout_block_level_children<'a>(
child_boxes: &'a [Arc<BlockLevelBox>],
containing_block: &ContainingBlock,
tree_rank: usize,
absolutely_positioned_fragments: &mut Vec<AbsolutelyPositionedFragment<'a>>,
float_context: Option<&mut FloatContext>,
collapsible_with_parent_start_margin: CollapsibleWithParentStartMargin,
) -> FlowChildren {
fn place_block_level_fragment(fragment: &mut Fragment, placement_state: &mut PlacementState) {
match fragment {
Fragment::Box(fragment) => {
let fragment_block_margins = &fragment.block_margins_collapsed_with_children;
let fragment_block_size = fragment.padding.block_sum()
+ fragment.border.block_sum()
+ fragment.content_rect.size.block;
if placement_state.next_in_flow_margin_collapses_with_parent_start_margin {
assert_eq!(placement_state.current_margin.solve(), Length::zero());
placement_state
.start_margin
.adjoin_assign(&fragment_block_margins.start);
if fragment_block_margins.collapsed_through {
placement_state
.start_margin
.adjoin_assign(&fragment_block_margins.end);
return;
}
placement_state.next_in_flow_margin_collapses_with_parent_start_margin = false;
} else {
placement_state
.current_margin
.adjoin_assign(&fragment_block_margins.start);
}
fragment.content_rect.start_corner.block += placement_state.current_margin.solve()
+ placement_state.current_block_direction_position;
if fragment_block_margins.collapsed_through {
placement_state
.current_margin
.adjoin_assign(&fragment_block_margins.end);
return;
}
placement_state.current_block_direction_position +=
placement_state.current_margin.solve() + fragment_block_size;
placement_state.current_margin = fragment_block_margins.end;
}
Fragment::Anonymous(fragment) => {
// FIXME(nox): Margin collapsing for hypothetical boxes of
// abspos elements is probably wrong.
assert!(fragment.children.is_empty());
assert_eq!(fragment.rect.size.block, Length::zero());
fragment.rect.start_corner.block +=
placement_state.current_block_direction_position;
}
_ => unreachable!(),
}
}
struct PlacementState {
next_in_flow_margin_collapses_with_parent_start_margin: bool,
start_margin: CollapsedMargin,
current_margin: CollapsedMargin,
current_block_direction_position: Length,
}
let abspos_so_far = absolutely_positioned_fragments.len();
let mut placement_state = PlacementState {
next_in_flow_margin_collapses_with_parent_start_margin:
collapsible_with_parent_start_margin.0,
start_margin: CollapsedMargin::zero(),
current_margin: CollapsedMargin::zero(),
current_block_direction_position: Length::zero(),
};
let mut fragments: Vec<_>;
if let Some(float_context) = float_context {
// Because floats are involved, we do layout for this block formatting context
// in tree order without parallelism. This enables mutable access
// to a `FloatContext` that tracks every float encountered so far (again in tree order).
fragments = child_boxes
.iter()
.enumerate()
.map(|(tree_rank, box_)| {
let mut fragment = box_.layout(
containing_block,
tree_rank,
absolutely_positioned_fragments,
Some(float_context),
);
place_block_level_fragment(&mut fragment, &mut placement_state);
fragment
})
.collect()
} else {
fragments = child_boxes
.par_iter()
.enumerate()
.mapfold_reduce_into(
absolutely_positioned_fragments,
|abspos_fragments, (tree_rank, box_)| {
box_.layout(
containing_block,
tree_rank,
abspos_fragments,
/* float_context = */ None,
)
},
|left_abspos_fragments, mut right_abspos_fragments| {
left_abspos_fragments.append(&mut right_abspos_fragments);
},
)
.collect();
for fragment in &mut fragments {
place_block_level_fragment(fragment, &mut placement_state)
}
}
adjust_static_positions(
&mut absolutely_positioned_fragments[abspos_so_far..],
&mut fragments,
tree_rank,
);
FlowChildren {
fragments,
block_size: placement_state.current_block_direction_position,
collapsible_margins_in_children: CollapsedBlockMargins {
collapsed_through: placement_state
.next_in_flow_margin_collapses_with_parent_start_margin,
start: placement_state.start_margin,
end: placement_state.current_margin,
},
}
}
impl BlockLevelBox {
fn layout<'a>(
&'a self,
containing_block: &ContainingBlock,
tree_rank: usize,
absolutely_positioned_fragments: &mut Vec<AbsolutelyPositionedFragment<'a>>,
float_context: Option<&mut FloatContext>,
) -> Fragment {
match self {
BlockLevelBox::SameFormattingContextBlock { style, contents } => {
Fragment::Box(layout_in_flow_non_replaced_block_level(
containing_block,
absolutely_positioned_fragments,
style,
BlockLevelKind::SameFormattingContextBlock,
|containing_block, nested_abspos, collapsible_with_parent_start_margin| {
contents.layout(
containing_block,
tree_rank,
nested_abspos,
float_context,
collapsible_with_parent_start_margin,
)
},
))
}
BlockLevelBox::Independent { style, contents } => match contents.as_replaced() {
Ok(replaced) => {
// FIXME
match *replaced {}
}
Err(contents) => Fragment::Box(layout_in_flow_non_replaced_block_level(
containing_block,
absolutely_positioned_fragments,
style,
BlockLevelKind::EstablishesAnIndependentFormattingContext,
|containing_block, nested_abspos, _| {
contents.layout(containing_block, tree_rank, nested_abspos)
},
)),
},
BlockLevelBox::OutOfFlowAbsolutelyPositionedBox(box_) => {
absolutely_positioned_fragments.push(box_.layout(Vec2::zero(), tree_rank));
Fragment::Anonymous(AnonymousFragment::no_op(containing_block.mode))
}
BlockLevelBox::OutOfFlowFloatBox(_box_) => {
// TODO
Fragment::Anonymous(AnonymousFragment::no_op(containing_block.mode))
}
}
}
}
#[derive(PartialEq)]
enum BlockLevelKind {
SameFormattingContextBlock,
EstablishesAnIndependentFormattingContext,
}
/// https://drafts.csswg.org/css2/visudet.html#blockwidth
/// https://drafts.csswg.org/css2/visudet.html#normal-block
fn layout_in_flow_non_replaced_block_level<'a>(
containing_block: &ContainingBlock,
absolutely_positioned_fragments: &mut Vec<AbsolutelyPositionedFragment<'a>>,
style: &Arc<ComputedValues>,
block_level_kind: BlockLevelKind,
layout_contents: impl FnOnce(
&ContainingBlock,
&mut Vec<AbsolutelyPositionedFragment<'a>>,
CollapsibleWithParentStartMargin,
) -> FlowChildren,
) -> BoxFragment {
let cbis = containing_block.inline_size;
let padding = style.padding().percentages_relative_to(cbis);
let border = style.border_width().percentages_relative_to(cbis);
let mut computed_margin = style.margin().percentages_relative_to(cbis);
let pb = &padding + &border;
let box_size = style.box_size();
let inline_size = box_size.inline.percentage_relative_to(cbis);
if let LengthOrAuto::Length(is) = inline_size {
let inline_margins = cbis - is - pb.inline_sum();
use LengthOrAuto::*;
match (
&mut computed_margin.inline_start,
&mut computed_margin.inline_end,
) {
(s @ &mut Auto, e @ &mut Auto) => {
*s = Length(inline_margins / 2.);
*e = Length(inline_margins / 2.);
}
(s @ &mut Auto, _) => {
*s = Length(inline_margins);
}
(_, e @ &mut Auto) => {
*e = Length(inline_margins);
}
(_, e @ _) => {
// Either the inline-end margin is auto,
// or were over-constrained and we do as if it were.
*e = Length(inline_margins);
}
}
}
let margin = computed_margin.auto_is(Length::zero);
let mut block_margins_collapsed_with_children = CollapsedBlockMargins::from_margin(&margin);
let inline_size = inline_size.auto_is(|| cbis - pb.inline_sum() - margin.inline_sum());
let block_size = match box_size.block {
LengthOrPercentageOrAuto::Length(l) => LengthOrAuto::Length(l),
LengthOrPercentageOrAuto::Percentage(p) => containing_block.block_size.map(|cbbs| cbbs * p),
LengthOrPercentageOrAuto::Auto => LengthOrAuto::Auto,
};
let containing_block_for_children = ContainingBlock {
inline_size,
block_size,
mode: style.writing_mode(),
};
// https://drafts.csswg.org/css-writing-modes/#orthogonal-flows
assert_eq!(
containing_block.mode, containing_block_for_children.mode,
"Mixed writing modes are not supported yet"
);
let this_start_margin_can_collapse_with_children = CollapsibleWithParentStartMargin(
block_level_kind == BlockLevelKind::SameFormattingContextBlock
&& pb.block_start == Length::zero(),
);
let this_end_margin_can_collapse_with_children = (block_level_kind, pb.block_end, block_size)
== (
BlockLevelKind::SameFormattingContextBlock,
Length::zero(),
LengthOrAuto::Auto,
);
let mut nested_abspos = vec![];
let mut flow_children = layout_contents(
&containing_block_for_children,
if style.box_.position.is_relatively_positioned() {
&mut nested_abspos
} else {
absolutely_positioned_fragments
},
this_start_margin_can_collapse_with_children,
);
if this_start_margin_can_collapse_with_children.0 {
block_margins_collapsed_with_children
.start
.adjoin_assign(&flow_children.collapsible_margins_in_children.start);
if flow_children
.collapsible_margins_in_children
.collapsed_through
{
block_margins_collapsed_with_children
.start
.adjoin_assign(&std::mem::replace(
&mut flow_children.collapsible_margins_in_children.end,
CollapsedMargin::zero(),
));
}
}
if this_end_margin_can_collapse_with_children {
block_margins_collapsed_with_children
.end
.adjoin_assign(&flow_children.collapsible_margins_in_children.end);
} else {
flow_children.block_size += flow_children.collapsible_margins_in_children.end.solve();
}
block_margins_collapsed_with_children.collapsed_through =
this_start_margin_can_collapse_with_children.0
&& this_end_margin_can_collapse_with_children
&& flow_children
.collapsible_margins_in_children
.collapsed_through;
let relative_adjustement = relative_adjustement(style, inline_size, block_size);
let block_size = block_size.auto_is(|| flow_children.block_size);
let content_rect = Rect {
start_corner: Vec2 {
block: pb.block_start + relative_adjustement.block,
inline: pb.inline_start + relative_adjustement.inline + margin.inline_start,
},
size: Vec2 {
block: block_size,
inline: inline_size,
},
};
if style.box_.position.is_relatively_positioned() {
AbsolutelyPositionedFragment::in_positioned_containing_block(
&nested_abspos,
&mut flow_children.fragments,
&content_rect.size,
&padding,
containing_block_for_children.mode,
)
}
BoxFragment {
style: style.clone(),
children: flow_children.fragments,
content_rect,
padding,
border,
margin,
block_margins_collapsed_with_children,
}
}

View file

@ -0,0 +1,122 @@
use super::*;
impl crate::dom::Document {
pub(crate) fn layout(
&self,
viewport: crate::primitives::Size<crate::primitives::CssPx>,
) -> Vec<Fragment> {
BoxTreeRoot::construct(self).layout(viewport)
}
}
struct BoxTreeRoot(BlockFormattingContext);
impl BoxTreeRoot {
pub fn construct(document: &dom::Document) -> Self {
let author_styles = &document.parse_stylesheets();
let context = Context {
document,
author_styles,
};
let root_element = document.root_element();
let style = style_for_element(context.author_styles, context.document, root_element, None);
let (contains_floats, boxes) = construct_for_root_element(&context, root_element, style);
Self(BlockFormattingContext {
contains_floats: contains_floats == ContainsFloats::Yes,
contents: BlockContainer::BlockLevelBoxes(boxes),
})
}
}
fn construct_for_root_element(
context: &Context,
root_element: dom::NodeId,
style: Arc<ComputedValues>,
) -> (ContainsFloats, Vec<Arc<BlockLevelBox>>) {
let replaced = ReplacedContent::for_element(root_element, context);
let display_inside = match style.box_.display {
Display::None => return (ContainsFloats::No, Vec::new()),
Display::Contents if replaced.is_some() => {
// 'display: contents' computes to 'none' for replaced elements
return (ContainsFloats::No, Vec::new());
}
// https://drafts.csswg.org/css-display-3/#transformations
Display::Contents => DisplayInside::Flow,
// The root element is blockified, ignore DisplayOutside
Display::GeneratingBox(DisplayGeneratingBox::OutsideInside { inside, .. }) => inside,
};
if let Some(replaced) = replaced {
let _box = match replaced {};
#[allow(unreachable_code)]
{
return (ContainsFloats::No, vec![Arc::new(_box)]);
}
}
let contents = IndependentFormattingContext::construct(
context,
&style,
display_inside,
Contents::OfElement(root_element),
);
if style.box_.position.is_absolutely_positioned() {
(
ContainsFloats::No,
vec![Arc::new(BlockLevelBox::OutOfFlowAbsolutelyPositionedBox(
AbsolutelyPositionedBox { style, contents },
))],
)
} else if style.box_.float.is_floating() {
(
ContainsFloats::Yes,
vec![Arc::new(BlockLevelBox::OutOfFlowFloatBox(FloatBox {
contents,
style,
}))],
)
} else {
(
ContainsFloats::No,
vec![Arc::new(BlockLevelBox::Independent { style, contents })],
)
}
}
impl BoxTreeRoot {
fn layout(&self, viewport: crate::primitives::Size<crate::primitives::CssPx>) -> Vec<Fragment> {
let initial_containing_block_size = Vec2 {
inline: Length { px: viewport.width },
block: Length {
px: viewport.height,
},
};
let initial_containing_block = ContainingBlock {
inline_size: initial_containing_block_size.inline,
block_size: LengthOrAuto::Length(initial_containing_block_size.block),
// FIXME: use the documents mode:
// https://drafts.csswg.org/css-writing-modes/#principal-flow
mode: (WritingMode::HorizontalTb, Direction::Ltr),
};
let dummy_tree_rank = 0;
let mut absolutely_positioned_fragments = vec![];
let mut flow_children = self.0.layout(
&initial_containing_block,
dummy_tree_rank,
&mut absolutely_positioned_fragments,
);
let initial_containing_block = DefiniteContainingBlock {
size: initial_containing_block_size,
mode: initial_containing_block.mode,
};
flow_children.fragments.par_extend(
absolutely_positioned_fragments
.par_iter()
.map(|a| a.layout(&initial_containing_block)),
);
flow_children.fragments
}
}