Truly independent web browser
LibWeb: Balance the columns of multi-column containers
Aliaksandr Kalenik97c2ddb6d10a
diff --git a/Libraries/LibWeb/Rust/src/css/computed_value_views.rs b/Libraries/LibWeb/Rust/src/css/computed_value_views.rsindex c86048c5657..d5f323df5d2 100644--- a/Libraries/LibWeb/Rust/src/css/computed_value_views.rs+++ b/Libraries/LibWeb/Rust/src/css/computed_value_views.rs@@ -424,6 +424,7 @@ scalar_accessors! {}misc_reset: {appearance: u8 => appearance,+ column_fill: u8 => column_fill,break_before: u8 => break_before,break_after: u8 => break_after,}diff --git a/Libraries/LibWeb/Rust/src/layout/block_formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/block_formatting_context.rsindex f8796845243..d5d07aa7fd0 100644--- a/Libraries/LibWeb/Rust/src/layout/block_formatting_context.rs+++ b/Libraries/LibWeb/Rust/src/layout/block_formatting_context.rs@@ -8,6 +8,8 @@use super::*;use smallvec::{SmallVec, smallvec};+const MAXIMUM_BALANCING_ROUNDS: usize = 16;+#[derive(Clone, Copy, Debug, PartialEq, Eq)]enum FragmentationStep {LayOut,@@ -2657,13 +2659,18 @@ impl<'pass> BlockFormattingContext<'pass> {}};- let column_block_size = definite_block_size;+ let column_block_size = self.column_block_size(input, column_input, geometry, definite_block_size);let mut incoming = None;let mut content_block_size = CssPixels::default();let mut column_index = 0;loop {- let (outcome, consumed_block_size) =- self.layout_column(column_input, column_block_size, incoming, column_origin(column_index));+ let (outcome, consumed_block_size) = self.layout_column(+ self.run.purpose,+ column_input,+ column_block_size,+ incoming,+ column_origin(column_index),+ );content_block_size = content_block_size.max(consumed_block_size);let Some(outgoing) = outcome.outgoing else {break;@@ -2678,14 +2685,144 @@ impl<'pass> BlockFormattingContext<'pass> {.set(Some(column_block_size.unwrap_or(content_block_size)));}+ fn column_block_size(+ &self,+ input: LayoutInput,+ column_input: LayoutInput,+ geometry: fragmentation::ColumnGeometry,+ definite_block_size: Option<CssPixels>,+ ) -> Option<CssPixels> {+ let root = self.run.box_;+ let style = self.style(root);+ let sizing = self.sizing();+ let constraints = input.containing_block_constraints;+ let own_size_space = AvailableSpace {+ block_size: constraints+ .percentage_basis_block_size+ .map_or(AvailableSize::Indefinite, AvailableSize::definite),+ ..input.available_space+ };+ let minimum_block_size = (definite_block_size.is_none()+ && !style.min_height().is_auto()+ && !style.min_height().is_intrinsic_sizing_constraint())+ .then(|| sizing.calculate_inner_block_size(root, own_size_space, style.min_height(), constraints));+ let maximum_block_size = definite_block_size.or_else(|| {+ (!sizing.should_treat_max_block_size_as_none(root, own_size_space.block_size, constraints)+ && !style.max_height().is_intrinsic_sizing_constraint())+ .then(|| {+ let maximum = sizing.calculate_inner_block_size(root, own_size_space, style.max_height(), constraints);+ minimum_block_size.map_or(maximum, |minimum| maximum.max(minimum))+ })+ });+ // https://drafts.csswg.org/css-multicol-1/#cf+ // auto: Fills columns sequentially.+ if style.column_fill() == column_fill::AUTO {+ return maximum_block_size;+ }+ Some(self.balanced_column_block_size(column_input, geometry, maximum_block_size))+ }++ fn balanced_column_block_size(+ &self,+ column_input: LayoutInput,+ geometry: fragmentation::ColumnGeometry,+ maximum_block_size: Option<CssPixels>,+ ) -> CssPixels {+ let clamp = |block_size: CssPixels| maximum_block_size.map_or(block_size, |maximum| block_size.min(maximum));++ let mut runs = Vec::new();+ let mut tallest_unbreakable_block_size = CssPixels::default();+ let mut incoming = None;+ loop {+ let (outcome, consumed_block_size) = self.layout_column(+ formatting_context::LayoutPurpose::Measurement,+ column_input,+ None,+ incoming,+ FfiCssPixelPoint::default(),+ );+ tallest_unbreakable_block_size = tallest_unbreakable_block_size.max(outcome.tallest_unbreakable_block_size);+ runs.push(consumed_block_size);+ incoming = outcome.outgoing;+ if incoming.is_none() || runs.len() >= fragmentation::MAXIMUM_COLUMN_COUNT {+ break;+ }+ }++ let mut implicit_breaks = vec![0usize; runs.len()];+ for _ in runs.len()..geometry.count {+ let tallest_run = (0..runs.len())+ .max_by_key(|&index| runs[index] / (implicit_breaks[index] + 1))+ .expect("content has at least one run");+ implicit_breaks[tallest_run] += 1;+ }+ let mut block_size = clamp(+ runs.iter()+ .zip(&implicit_breaks)+ .map(|(&run, &breaks)| fragmentation::ceil_divide(run, breaks + 1))+ .max()+ .unwrap_or_default()+ .max(tallest_unbreakable_block_size),+ );+ if runs.len() >= geometry.count {+ return block_size;+ }++ for _ in 0..MAXIMUM_BALANCING_ROUNDS {+ let mut incoming = None;+ let mut column_count = 0;+ let mut forced_break_count = 0;+ let mut minimal_space_shortage: Option<CssPixels> = None;+ loop {+ let (outcome, _) = self.layout_column(+ formatting_context::LayoutPurpose::Measurement,+ column_input,+ Some(block_size),+ incoming,+ FfiCssPixelPoint::default(),+ );+ column_count += 1;+ if outcome.ended_at_forced_break() {+ forced_break_count += 1;+ }+ if let Some(shortage) = outcome.minimal_space_shortage {+ minimal_space_shortage =+ Some(minimal_space_shortage.map_or(shortage, |minimal| minimal.min(shortage)));+ }+ incoming = outcome.outgoing;+ if incoming.is_none() || column_count > geometry.count {+ break;+ }+ }+ if incoming.is_none() && column_count <= geometry.count {+ break;+ }+ if forced_break_count + 1 >= geometry.count {+ break;+ }+ let Some(shortage) = minimal_space_shortage else {+ break;+ };+ let next_block_size = clamp(block_size + shortage);+ if next_block_size <= block_size {+ break;+ }+ block_size = next_block_size;+ }+ block_size+ }+fn layout_column(&self,+ purpose: formatting_context::LayoutPurpose,input: LayoutInput,block_size: Option<CssPixels>,incoming: Option<std::rc::Rc<fragmentation::BlockBreakToken>>,origin: FfiCssPixelPoint,) -> (fragmentation::FragmentainerOutcome, CssPixels) {let mut early_break_before = None;+ let mut minimal_space_shortage_of_discarded_attempts = None;+ let mut tallest_unbreakable_block_size_of_discarded_attempts = CssPixels::default();loop {let fragmentainer = std::rc::Rc::new(fragmentation::FragmentainerContext::new(block_size,@@ -2697,21 +2834,35 @@ impl<'pass> BlockFormattingContext<'pass> {if journals_stored_entries {fc_run_cache_store.begin_store_journal();}- let outputs = formatting_context::run_fragmentainer(&self.run, input, fragmentainer.clone());- let outcome = fragmentainer.take_outcome();+ let outputs = formatting_context::run_fragmentainer(&self.run, purpose, input, fragmentainer.clone());+ let mut outcome = fragmentainer.take_outcome();let retries = outcome.needs_early_break_before.is_some_and(|node| early_break_before != Some(node));if journals_stored_entries {fc_run_cache_store.end_store_journal(!retries);}+ outcome.minimal_space_shortage = match (+ outcome.minimal_space_shortage,+ minimal_space_shortage_of_discarded_attempts,+ ) {+ (Some(left), Some(right)) => Some(left.min(right)),+ (left, right) => left.or(right),+ };+ outcome.tallest_unbreakable_block_size = outcome+ .tallest_unbreakable_block_size+ .max(tallest_unbreakable_block_size_of_discarded_attempts);if let Some(node) = outcome.needs_early_break_before&& early_break_before != Some(node){early_break_before = Some(node);+ minimal_space_shortage_of_discarded_attempts = outcome.minimal_space_shortage;+ tallest_unbreakable_block_size_of_discarded_attempts = outcome.tallest_unbreakable_block_size;continue;}- if let (Some(fragments), Some(root)) = (self.run.fragments.as_deref(), outputs.root) {+ if purpose == formatting_context::LayoutPurpose::Commit+ && let (Some(fragments), Some(root)) = (self.run.fragments.as_deref(), outputs.root)+ {fragments.adopt_fragmentainer_root(root, origin);}return (outcome, outputs.result.automatic_content_block_size);diff --git a/Libraries/LibWeb/Rust/src/layout/formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/formatting_context.rsindex 39a878e7578..6f421697d74 100644--- a/Libraries/LibWeb/Rust/src/layout/formatting_context.rs+++ b/Libraries/LibWeb/Rust/src/layout/formatting_context.rs@@ -188,6 +188,7 @@ impl<'pass> MeasurementState<'pass> {pub(crate) fn run_fragmentainer(outer: &FormattingContextRun,+ purpose: LayoutPurpose,input: LayoutInput,fragmentainer: std::rc::Rc<fragmentation::FragmentainerContext>,) -> RunOutputs {@@ -197,7 +198,7 @@ pub(crate) fn run_fragmentainer(.callbacks.containing_block_for_child_run(box_, &input.participation);execute_formatting_context_run(- outer.purpose,+ purpose,used_values::UsedValuesCellState::capture(outer.records.used_values(box_)),box_,root_containing_block,diff --git a/Libraries/LibWeb/Rust/src/layout/fragmentation.rs b/Libraries/LibWeb/Rust/src/layout/fragmentation.rsindex 8e7b17b158b..2c1a2d260ec 100644--- a/Libraries/LibWeb/Rust/src/layout/fragmentation.rs+++ b/Libraries/LibWeb/Rust/src/layout/fragmentation.rs@@ -73,6 +73,11 @@ pub(crate) fn resolve_column_geometry(style: StyleValues<'_>, available_inline_s}}+pub(crate) fn ceil_divide(value: CssPixels, divisor: usize) -> CssPixels {+ let divisor = divisor.max(1) as i64;+ CssPixels::from_raw(((value.raw_value() as i64 + divisor - 1).div_euclid(divisor)) as i32)+}+pub(crate) fn is_forced_column_break(value: u8) -> bool {value == break_between::COLUMN}@@ -96,6 +101,14 @@ pub(crate) struct FragmentainerOutcome {pub(crate) tallest_unbreakable_block_size: CssPixels,}+impl FragmentainerOutcome {+ pub(crate) fn ended_at_forced_break(&self) -> bool {+ self.outgoing.as_ref().is_some_and(|token| match token.resume {+ BlockResume::BeforeChild { after_forced_break, .. } => after_forced_break,+ })+ }+}+pub(crate) struct FragmentainerContext {pub(crate) block_size: Option<CssPixels>,pub(crate) incoming: Option<Rc<BlockBreakToken>>,diff --git a/Tests/LibWeb/Crash/Layout/multicol-huge-column-count.html b/Tests/LibWeb/Crash/Layout/multicol-huge-column-count.htmlnew file mode 100644index 00000000000..62057e69954--- /dev/null+++ b/Tests/LibWeb/Crash/Layout/multicol-huge-column-count.html@@ -0,0 +1,26 @@+<!DOCTYPE html>+<style>+ .huge-count {+ column-count: 2000000000;+ }+ .huge-count > div {+ height: 20px;+ }+ .break {+ break-before: column;+ }+ .narrow-width {+ width: 100000000px;+ column-width: 1px;+ column-gap: 0;+ }+</style>+<div class="huge-count">+ <div></div>+ <div class="break"></div>+ <div class="break"></div>+ <div class="break"></div>+</div>+<div class="narrow-width">+ <div style="height: 100px"></div>+</div>diff --git a/Tests/LibWeb/Ref/expected/multicol-balance-block-children-ref.html b/Tests/LibWeb/Ref/expected/multicol-balance-block-children-ref.htmlnew file mode 100644index 00000000000..841aacc2600--- /dev/null+++ b/Tests/LibWeb/Ref/expected/multicol-balance-block-children-ref.html@@ -0,0 +1,14 @@+<!DOCTYPE html>+<style>+body { margin: 0; }+.container { position: relative; height: 60px; width: 320px; background: lightgray; }+.container > div { position: absolute; width: 100px; height: 20px; }+</style>+<div class="container">+ <div style="background: red; left: 0; top: 0; height: 50px"></div>+ <div style="background: orange; left: 110px; top: 0"></div>+ <div style="background: yellow; left: 110px; top: 20px"></div>+ <div style="background: green; left: 110px; top: 40px"></div>+ <div style="background: blue; left: 220px; top: 0; height: 50px"></div>+</div>+<div style="height: 10px; background: black"></div>diff --git a/Tests/LibWeb/Ref/expected/multicol-balance-min-max-height-ref.html b/Tests/LibWeb/Ref/expected/multicol-balance-min-max-height-ref.htmlnew file mode 100644index 00000000000..f5831e4bba1--- /dev/null+++ b/Tests/LibWeb/Ref/expected/multicol-balance-min-max-height-ref.html@@ -0,0 +1,15 @@+<!DOCTYPE html>+<style>+body { margin: 0; }+.container { position: relative; width: 220px; background: lightgray; margin-bottom: 10px; }+.container > div { position: absolute; width: 100px; height: 20px; background: green; }+</style>+<div class="container" style="height: 80px">+ <div style="left: 0; top: 0; height: 60px"></div>+ <div style="left: 120px; top: 0; height: 60px"></div>+</div>+<div class="container" style="height: 40px">+ <div style="left: 0; top: 0; height: 40px"></div>+ <div style="left: 120px; top: 0; height: 40px"></div>+ <div style="left: 240px; top: 0; height: 40px"></div>+</div>diff --git a/Tests/LibWeb/Ref/input/multicol-balance-block-children.html b/Tests/LibWeb/Ref/input/multicol-balance-block-children.htmlnew file mode 100644index 00000000000..5a2a66beebd--- /dev/null+++ b/Tests/LibWeb/Ref/input/multicol-balance-block-children.html@@ -0,0 +1,15 @@+<!DOCTYPE html>+<link rel="match" href="../expected/multicol-balance-block-children-ref.html">+<style>+body { margin: 0; }+.multicol { columns: 3; column-gap: 10px; width: 320px; background: lightgray; }+.multicol > div { height: 20px; overflow: hidden; }+</style>+<div class="multicol">+ <div style="background: red; height: 50px"></div>+ <div style="background: orange"></div>+ <div style="background: yellow"></div>+ <div style="background: green"></div>+ <div style="background: blue; height: 50px"></div>+</div>+<div style="height: 10px; background: black"></div>diff --git a/Tests/LibWeb/Ref/input/multicol-balance-min-max-height.html b/Tests/LibWeb/Ref/input/multicol-balance-min-max-height.htmlnew file mode 100644index 00000000000..b049cedab41--- /dev/null+++ b/Tests/LibWeb/Ref/input/multicol-balance-min-max-height.html@@ -0,0 +1,13 @@+<!DOCTYPE html>+<link rel="match" href="../expected/multicol-balance-min-max-height-ref.html">+<style>+body { margin: 0; }+.multicol { columns: 2; column-gap: 20px; width: 220px; background: lightgray; margin-bottom: 10px; }+.multicol > div { height: 20px; background: green; }+</style>+<div class="multicol" style="min-height: 80px">+ <div></div><div></div><div></div><div></div><div></div><div></div>+</div>+<div class="multicol" style="max-height: 40px">+ <div></div><div></div><div></div><div></div><div></div><div></div>+</div>diff --git a/Tests/LibWeb/Text/expected/multicol-anonymous-content-box-columns.txt b/Tests/LibWeb/Text/expected/multicol-anonymous-content-box-columns.txtnew file mode 100644index 00000000000..77bfe61f3d7--- /dev/null+++ b/Tests/LibWeb/Text/expected/multicol-anonymous-content-box-columns.txt@@ -0,0 +1,5 @@+button-on: 150,0 150x20+button-off: 0,20 300x20+fieldset-on: 150,10 150x20+legend-removed: 150,0 150x20+legend-added: 150,10 150x20diff --git a/Tests/LibWeb/Text/expected/multicol-column-transition-on-content-box.txt b/Tests/LibWeb/Text/expected/multicol-column-transition-on-content-box.txtnew file mode 100644index 00000000000..b3913da593c--- /dev/null+++ b/Tests/LibWeb/Text/expected/multicol-column-transition-on-content-box.txt@@ -0,0 +1,2 @@+fieldset-block: 260 160+button-block: 260 160diff --git a/Tests/LibWeb/Text/input/multicol-anonymous-content-box-columns.html b/Tests/LibWeb/Text/input/multicol-anonymous-content-box-columns.htmlnew file mode 100644index 00000000000..1a256938f2c--- /dev/null+++ b/Tests/LibWeb/Text/input/multicol-anonymous-content-box-columns.html@@ -0,0 +1,31 @@+<!DOCTYPE html>+<script src="include.js"></script>+<style>+ body { margin: 0; }+ button { display: block; width: 300px; column-gap: 0; padding: 0; border: 0; margin: 0; }+ fieldset { width: 300px; column-gap: 0; padding: 0; border: 0; margin: 0; }+ legend { padding: 0; height: 10px; }+ .item { height: 20px; }+</style>+<button id="button-on"><div class="item"></div><div class="item" id="button-on-second"></div></button>+<button id="button-off" style="column-count: 2"><div class="item"></div><div class="item" id="button-off-second"></div></button>+<fieldset id="fieldset-on"><legend>L</legend><div class="item"></div><div class="item" id="fieldset-on-second"></div></fieldset>+<fieldset id="legend-removed" style="column-count: 2"><legend id="removed-legend">L</legend><div class="item"></div><div class="item" id="legend-removed-second"></div></fieldset>+<fieldset id="legend-added" style="column-count: 2"><div class="item"></div><div class="item" id="legend-added-second"></div></fieldset>+<script>+ test(() => {+ document.body.offsetWidth;+ document.getElementById("button-on").style.columnCount = "2";+ document.getElementById("button-off").style.columnCount = "auto";+ document.getElementById("fieldset-on").style.columnCount = "2";+ document.getElementById("removed-legend").remove();+ const legend = document.createElement("legend");+ legend.textContent = "L";+ document.getElementById("legend-added").prepend(legend);+ for (const id of ["button-on", "button-off", "fieldset-on", "legend-removed", "legend-added"]) {+ const origin = document.getElementById(id).getBoundingClientRect();+ const rect = document.getElementById(`${id}-second`).getBoundingClientRect();+ println(`${id}: ${rect.x - origin.x},${rect.y - origin.y} ${rect.width}x${rect.height}`);+ }+ });+</script>diff --git a/Tests/LibWeb/Text/input/multicol-column-transition-on-content-box.html b/Tests/LibWeb/Text/input/multicol-column-transition-on-content-box.htmlnew file mode 100644index 00000000000..3291dc3d0ca--- /dev/null+++ b/Tests/LibWeb/Text/input/multicol-column-transition-on-content-box.html@@ -0,0 +1,24 @@+<!DOCTYPE html>+<script src="include.js"></script>+<style>+ body { margin: 0; }+ .multicol { columns: 2; width: 420px; column-gap: 0px; margin: 0; padding: 0; border: 0; display: block; transition: column-gap 1000s linear -500s; }+ .multicol.wide { column-gap: 200px; }+ .block { height: 40px; }+ legend { padding: 0; }+</style>+<fieldset class="multicol" id="fieldset"><legend>L</legend><div class="block"></div><div class="block" id="fieldset-block"></div></fieldset>+<button class="multicol" id="button"><div class="block"></div><div class="block" id="button-block"></div></button>+<script>+ test(() => {+ document.body.offsetWidth;+ for (const id of ["fieldset", "button"])+ document.getElementById(id).classList.add("wide");+ for (const id of ["fieldset-block", "button-block"]) {+ const element = document.getElementById(id);+ const origin = element.parentElement.getBoundingClientRect();+ const rect = element.getBoundingClientRect();+ println(`${id}: ${rect.x - origin.x} ${rect.width}`);+ }+ });+</script>