Truly independent web browser
LibWeb: Look up a document's initial groups before computing them
Andreas Klingedfd3b8fd96e
diff --git a/Libraries/LibWeb/Rust/src/css/computed_longhand_table.rs b/Libraries/LibWeb/Rust/src/css/computed_longhand_table.rsindex 411ce79a402..e5eeced5bf2 100644--- a/Libraries/LibWeb/Rust/src/css/computed_longhand_table.rs+++ b/Libraries/LibWeb/Rust/src/css/computed_longhand_table.rs@@ -72,7 +72,7 @@ fn set_bitmap_bit(bits: &mut [u8; LONGHAND_BITMAP_BYTES], index: usize, value: b/// box display, color scheme and dependency flags: whether each longhand's value was important,/// inherited or evaluated by the computation, and what the box adjustments and monospace/// recascades read.-#[derive(Clone)]+#[derive(Clone, PartialEq)]pub(crate) struct LonghandTableFlags {important_bits: [u8; LONGHAND_BITMAP_BYTES],inherited_bits: [u8; LONGHAND_BITMAP_BYTES],diff --git a/Libraries/LibWeb/Rust/src/css/computed_values.rs b/Libraries/LibWeb/Rust/src/css/computed_values.rsindex a4c4fa27430..8a0f2d0d6f6 100644--- a/Libraries/LibWeb/Rust/src/css/computed_values.rs+++ b/Libraries/LibWeb/Rust/src/css/computed_values.rs@@ -4894,6 +4894,11 @@ unsafe impl Send for HeldGroup {}unsafe impl Sync for HeldGroup {}impl HeldGroup {+ /// The payload, whose reference goes to the caller.+ pub(crate) fn into_retained(self) -> *const c_void {+ std::mem::ManuallyDrop::new(self).payload+ }+/// The group `payload`, a payload of the group at `group`, taking over the caller's/// reference to it.///diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/compute.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/compute.rsindex 6045a3cb544..70e33247a4c 100644--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/compute.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/compute.rs@@ -6,6 +6,7 @@//! The engine's computation of one element's style from the winners its cascade decided.+use super::super::process_style::{InitialGroupsInputs, SharedInitialGroups};use super::super::publication::pseudo_kind;use super::super::*;use super::cascade::Winner;@@ -127,6 +128,18 @@ impl RetainedState {pub(in crate::css::style) fn initial_style(&self,root: StyleNodeID,+ ) -> Result<ComputedInitialStyle, Option<Box<font_resolution::FontRequest>>> {+ let inputs = InitialGroupsInputs::of(&self.document_style_computation_inputs);+ match self.process_style.initial_groups_of(&inputs) {+ Some(shared) => self.initial_style_over(root, &shared),+ None => self.initial_style_driven(root),+ }+ }++ /// The initial values computed from nothing: every longhand is driven and every group built.+ fn initial_style_driven(+ &self,+ root: StyleNodeID,) -> Result<ComputedInitialStyle, Option<Box<font_resolution::FontRequest>>> {let subject = DriveSubject {target: computed::ComputedStyleTarget::new(root, u8::MAX),@@ -183,9 +196,12 @@ impl RetainedState {first_available_font: font.first_available_font as usize,font_cascade_list: font.font_cascade_list as usize,};+ let value_facts = values.facts().clone();Ok(ComputedInitialStyle {payloads,- value_facts: values.into_facts(),+ value_groups: Some(values.into_groups()),+ shared: None,+ value_facts,flags,dependency_flags,color: color_inputs.1,@@ -200,6 +216,137 @@ impl RetainedState {})}+ /// The initial values another document computed from what this one computes them from, which+ /// `shared` holds: only the font group holds anything of this document, its fonts.+ fn initial_style_over(+ &self,+ root: StyleNodeID,+ shared: &Arc<SharedInitialGroups>,+ ) -> Result<ComputedInitialStyle, Option<Box<font_resolution::FontRequest>>> {+ use crate::css::computed_values::StyleGroupIndex;+ use crate::css::table_group_builder::group_index;+ let subject = DriveSubject {+ target: computed::ComputedStyleTarget::new(root, u8::MAX),+ parent: None,+ facts: 0,+ };+ let store = WinnerStore::new(Vec::new());+ let inputs = self.document_style_computation_inputs;+ let mut font_scratch = drive::FontDriveScratch::default();+ let held = shared.values();+ let seed = crate::css::computed_values::GroupSeed::new(shared.seed_groups(), &held.value_facts);+ let writer = GroupValuesWriter::seeded_for_child(+ seed,+ seed,+ std::iter::empty(),+ held.flags.clone(),+ held.dependency_flags,+ );+ let selected = [0_u64; crate::css::property_metadata::LONGHAND_WORD_COUNT];+ let driven = self.engine_drive_with(+ self,+ subject,+ writer,+ Some(&selected),+ &store,+ &inputs,+ &mut font_scratch,+ );+ let (writer, length, font) = match driven {+ Ok(drive::DrivenValues {+ writer,+ length,+ font: Some(font),+ }) => (writer, length, font),+ Err(Unanswered::Suspended(Suspension::Font)) => {+ return Err(Some(Box::new(font_scratch.take_suspended_request())));+ }+ _ => return Err(None),+ };+ let (values, _, _) = writer.finish(&[seed]);+ let source = crate::css::table_group_builder::LonghandSource::Values {+ values: &values,+ reads: None,+ };+ let color_inputs = crate::css::table_group_builder::assembly_color_inputs_from_source(&source, &length);+ let mut payloads = std::array::from_fn(|group| match group == group_index::FONT {+ // SAFETY: The values are those of an element with no parent.+ true => unsafe {+ crate::css::table_group_builder::assemble_group_from_source(+ &source,+ group_index::FONT,+ Some(&font),+ crate::css::computed_values::GroupShares::new(+ &self.process_style.default_groups,+ group_index::FONT,+ None,+ ),+ color_inputs,+ &length,+ )+ },+ false => shared+ .groups()+ .group(StyleGroupIndex::new(group))+ .held()+ .into_retained(),+ });+ // SAFETY: Each payload is a live payload of its group, whose reference the style takes, and the groups+ // but the font group hold the values already.+ unsafe { values.put_into(&mut payloads, !(1 << group_index::FONT)) };+ let initial_font = super::traversal::InitialFont {+ first_available_font: font.first_available_font as usize,+ font_cascade_list: font.font_cascade_list as usize,+ };+ let computed = ComputedInitialStyle {+ payloads,+ value_groups: None,+ value_facts: held.value_facts.clone(),+ flags: held.flags.clone(),+ dependency_flags: held.dependency_flags,+ color: held.color,+ font: initial_font,+ shared: None,+ };+ if self.process_style.verifies_reads {+ self.verify_initial_style_over(root, shared, &computed, color_inputs.1);+ }+ Ok(ComputedInitialStyle {+ shared: Some(Arc::clone(shared)),+ ..computed+ })+ }++ /// Check that driving every longhand computes what the shared groups hold for this document.+ fn verify_initial_style_over(+ &self,+ root: StyleNodeID,+ shared: &SharedInitialGroups,+ computed: &ComputedInitialStyle,+ color: u32,+ ) {+ let Ok(driven) = self.initial_style_driven(root) else {+ return;+ };+ // SAFETY: The groups take over the references the drive made.+ let groups = unsafe {+ crate::css::computed_values::StyleGroups::adopt(+ driven.payloads,+ crate::css::computed_value_types::StyleBits::INITIAL,+ )+ };+ assert!(+ shared.hold_the_same_as(&groups)+ && driven.flags == computed.flags+ && driven.dependency_flags == computed.dependency_flags+ && driven.color == color+ && driven.color == computed.color+ && driven.value_facts.publication_equals(&computed.value_facts)+ && driven.font == computed.font,+ "a document's initial values are those of the documents it shares initial groups with"+ );+ }+/// The engine: compute the record of `node` from the cascade winners it decided, against the/// records `records` holds for its ancestors, into a table seeded from `initial` and the/// inherited values of the parent's table. A winner the engine computes directly absolutizes@@ -2035,6 +2182,10 @@ pub(in crate::css::style) struct GroupSeeds<'a> {/// The initial values as a drive computes them, with a reference to each payload.pub(in crate::css::style) struct ComputedInitialStyle {pub(in crate::css::style) payloads: [*const std::ffi::c_void; crate::css::table_group_builder::group_index::COUNT],+ /// The groups of the initial values, with no font in them, where a drive computed them.+ pub(in crate::css::style) value_groups: Option<crate::css::computed_values::StyleGroups>,+ /// The groups of the process the values were found in, where they were.+ pub(in crate::css::style) shared: Option<Arc<SharedInitialGroups>>,pub(in crate::css::style) value_facts: crate::css::computed_values::GroupValueFacts,pub(in crate::css::style) flags: crate::css::computed_longhand_table::LonghandTableFlags,pub(in crate::css::style) dependency_flags: u8,diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/mod.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/mod.rsindex 3f09b8242e0..3d0df82c2ab 100644--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/mod.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/mod.rs@@ -192,7 +192,7 @@ impl StyleEngine {// have asked the resolver for yet.self.until_resolved(root, |engine| {match engine.retained.initial_style(root) {- Ok(computed) => {+ Ok(mut computed) => {// SAFETY: The initial style takes over the references the drive made.let mut payloads = unsafe {crate::css::computed_values::StyleGroups::adopt(@@ -207,18 +207,31 @@ impl StyleEngine {)};// The documents of the process share the initial groups but the font group.- let shared = engine.retained.process_style.share_initial_groups(- engine- .retained- .document_style_computation_inputs- .device_pixels_per_css_pixel,- &payloads,- );- for index in crate::css::computed_values::StyleGroupIndex::all() {- if index.usize() != crate::css::table_group_builder::group_index::FONT {- payloads.share_group(shared.groups(), index);+ let shared = computed.shared.take().unwrap_or_else(|| {+ let value_groups = computed+ .value_groups+ .take()+ .expect("a drive made the groups of its values");+ let shared = engine.retained.process_style.share_initial_groups(+ super::process_style::InitialGroupsInputs::of(+ &engine.retained.document_style_computation_inputs,+ ),+ &payloads,+ &value_groups,+ super::process_style::InitialGroupsValues {+ flags: computed.flags.clone(),+ dependency_flags: computed.dependency_flags,+ color: computed.color,+ value_facts: computed.value_facts.clone(),+ },+ );+ for index in crate::css::computed_values::StyleGroupIndex::all() {+ if index.usize() != crate::css::table_group_builder::group_index::FONT {+ payloads.share_group(shared.groups(), index);+ }}- }+ shared+ });Ok(Some(traversal::InitialStyle::new(computed, payloads, shared)))}// NB: An engine no host published its fonts to yet, such as a test's bare engine, has no resolverdiff --git a/Libraries/LibWeb/Rust/src/css/style/process_style.rs b/Libraries/LibWeb/Rust/src/css/style/process_style.rsindex 40635193b5f..58e2f5c1232 100644--- a/Libraries/LibWeb/Rust/src/css/style/process_style.rs+++ b/Libraries/LibWeb/Rust/src/css/style/process_style.rs@@ -30,9 +30,8 @@ pub(crate) struct ProcessStyle {pub(super) rule_indexes: pipeline::ProcessRuleIndexes,/// The fact lists of every document's projection rows, interned by content.pub(super) fact_lists: Mutex<pipeline::projection::FactListsTable>,- /// The initial groups the documents of the process share, by the device pixel ratio lengths- /// snap by, which every initial length computes against.- initial_groups: Mutex<HashMap<u64, Vec<std::sync::Weak<SharedInitialGroups>>>>,+ /// The initial groups the documents of the process share, one entry for what each computed from.+ initial_groups: Mutex<Vec<std::sync::Weak<SharedInitialGroups>>>,/// The groups of default values every computation starting from nothing starts from.pub(super) default_groups: crate::css::computed_values::DefaultGroups,/// Whether what is read of an element's values is checked against what its groups build from@@ -40,18 +39,78 @@ pub(crate) struct ProcessStyle {pub(super) verifies_reads: bool,}+/// What a document's initial values compute from, which documents agreeing on it share the groups+/// of: the lengths its initial values snap by and its initial font's metrics and sizes, and the+/// color scheme the initial color resolves against.+#[derive(Clone, Copy, PartialEq, Eq)]+pub(super) struct InitialGroupsInputs {+ device_pixels_per_css_pixel: u64,+ initial_font_metrics: [u64; 5],+ initial_font_size_raw: i32,+ default_font_size_raw: i32,+ effective_color_scheme: u8,+}++impl InitialGroupsInputs {+ pub(super) fn of(inputs: &bridge::FfiDocumentStyleComputationInputs) -> Self {+ Self {+ device_pixels_per_css_pixel: inputs.device_pixels_per_css_pixel.to_bits(),+ initial_font_metrics: [+ inputs.initial_font_size,+ inputs.initial_font_x_height,+ inputs.initial_font_cap_height,+ inputs.initial_font_zero_advance,+ inputs.initial_line_height,+ ]+ .map(f64::to_bits),+ initial_font_size_raw: inputs.initial_font_size_raw,+ default_font_size_raw: inputs.default_font_size_raw,+ effective_color_scheme: crate::css::style_compute::resolve_effective_color_scheme(+ &[],+ inputs.preferred_color_scheme,+ inputs.has_document_supported_schemes.then(|| {+ &inputs.document_supported_scheme_codes[..usize::from(inputs.document_supported_scheme_count)]+ }),+ ),+ }+ }+}++/// What a document's initial values compute to, besides what its font group holds of its fonts.+pub(super) struct InitialGroupsValues {+ pub(super) flags: crate::css::computed_longhand_table::LonghandTableFlags,+ pub(super) dependency_flags: u8,+ pub(super) color: u32,+ pub(super) value_facts: crate::css::computed_values::GroupValueFacts,+}+/// The initial groups the documents of the process share: each group of a document's initial/// style but its font group, which holds the fonts of its document's font computer and is the/// default one here.-pub(super) struct SharedInitialGroups(crate::css::computed_values::StyleGroups);+pub(super) struct SharedInitialGroups {+ inputs: InitialGroupsInputs,+ groups: crate::css::computed_values::StyleGroups,+ /// These groups with the font values of the initial style in the font group, which is built+ /// from no fonts: what a document computes its own font group from.+ seed_groups: crate::css::computed_values::StyleGroups,+ values: InitialGroupsValues,+}impl SharedInitialGroups {pub(super) fn groups(&self) -> &crate::css::computed_values::StyleGroups {- &self.0+ &self.groups+ }++ pub(super) fn seed_groups(&self) -> &crate::css::computed_values::StyleGroups {+ &self.seed_groups+ }++ pub(super) fn values(&self) -> &InitialGroupsValues {+ &self.values}/// Whether each group of `groups` but the font group holds what this one does.- fn hold_the_same_as(&self, groups: &crate::css::computed_values::StyleGroups) -> bool {+ pub(super) fn hold_the_same_as(&self, groups: &crate::css::computed_values::StyleGroups) -> bool {use crate::css::computed_values::StyleGroupIndex;use crate::css::table_group_builder::group_index;StyleGroupIndex::all()@@ -61,7 +120,7 @@ impl SharedInitialGroups {unsafe {crate::css::computed_values::groups_hold_the_same(index.usize(),- self.0[index.usize()].as_ptr(),+ self.groups[index.usize()].as_ptr(),groups[index.usize()].as_ptr(),)}@@ -93,14 +152,26 @@ impl ProcessStyle {}impl ProcessStyle {+ /// The initial groups another document of the process computed from `inputs`, if one is alive.+ pub(super) fn initial_groups_of(&self, inputs: &InitialGroupsInputs) -> Option<Arc<SharedInitialGroups>> {+ self.initial_groups+ .lock()+ .expect("the initial groups lock is not poisoned")+ .iter()+ .filter_map(std::sync::Weak::upgrade)+ .find(|shared| shared.inputs == *inputs)+ }+/// The initial groups the documents of the process share that hold what `groups`, a- /// document's initial groups computed under the device pixel ratio- /// `device_pixels_per_css_pixel`, hold besides its font group: the ones another document- /// computed, or these.+ /// document's initial groups computed from `inputs`, hold besides its font group: those of+ /// another document's where they hold the same. `value_groups` are the groups of those values,+ /// with no font in them.pub(super) fn share_initial_groups(&self,- device_pixels_per_css_pixel: f64,+ inputs: InitialGroupsInputs,groups: &crate::css::computed_values::StyleGroups,+ value_groups: &crate::css::computed_values::StyleGroups,+ values: InitialGroupsValues,) -> Arc<SharedInitialGroups> {use crate::css::computed_values::StyleGroupIndex;use crate::css::table_group_builder::group_index;@@ -108,20 +179,30 @@ impl ProcessStyle {.initial_groups.lock().expect("the initial groups lock is not poisoned");- let shared = initial_groups.entry(device_pixels_per_css_pixel.to_bits()).or_default();- shared.retain(|entry| entry.strong_count() != 0);- if let Some(shared) = shared+ initial_groups.retain(|entry| entry.strong_count() != 0);+ let same = initial_groups.iter().filter_map(std::sync::Weak::upgrade)- .find(|shared| shared.hold_the_same_as(groups))- {- return shared;- }- // NB: The font group is the default one, so that no document's fonts outlive it here.- let mut own = groups.clone();- own.share_group(self.default_groups.groups(), StyleGroupIndex::new(group_index::FONT));- let own = Arc::new(SharedInitialGroups(own));- shared.push(Arc::downgrade(&own));+ .find(|shared| shared.hold_the_same_as(groups));+ let font = StyleGroupIndex::new(group_index::FONT);+ let own_groups = same.as_ref().map_or_else(+ || {+ // NB: The font group is the default one, so that no document's fonts outlive it here.+ let mut own = groups.clone();+ own.share_group(self.default_groups.groups(), font);+ own+ },+ |same| same.groups.clone(),+ );+ let mut seed_groups = own_groups.clone();+ seed_groups.share_group(value_groups, font);+ let own = Arc::new(SharedInitialGroups {+ inputs,+ groups: own_groups,+ seed_groups,+ values,+ });+ initial_groups.push(Arc::downgrade(&own));own}diff --git a/Libraries/LibWeb/Rust/src/css/style_compute/adjustments.rs b/Libraries/LibWeb/Rust/src/css/style_compute/adjustments.rsindex d10470af866..e688604c840 100644--- a/Libraries/LibWeb/Rust/src/css/style_compute/adjustments.rs+++ b/Libraries/LibWeb/Rust/src/css/style_compute/adjustments.rs@@ -447,7 +447,7 @@ pub(super) fn resolve_effective_overflow_keywords(overflow_x: u16, overflow_y: u}// https://drafts.csswg.org/css-color-adjust-1/#determine-the-used-color-scheme-pub(super) fn resolve_effective_color_scheme(+pub(crate) fn resolve_effective_color_scheme(schemes: &[u8],preferred_scheme: u8,document_supported_schemes: Option<&[u8]>,diff --git a/Tests/LibWeb/Text/expected/css/style-engine/initial-style-across-documents.txt b/Tests/LibWeb/Text/expected/css/style-engine/initial-style-across-documents.txtnew file mode 100644index 00000000000..dbd4339d9d8--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-engine/initial-style-across-documents.txt@@ -0,0 +1,7 @@+no-quirks: color: rgb(0, 0, 0); background-color: rgba(0, 0, 0, 0); color-scheme: normal; font-size: 16px; line-height: normal; display: block; margin-top: 0px+quirks: color: rgb(0, 0, 0); background-color: rgba(0, 0, 0, 0); color-scheme: normal; font-size: 16px; line-height: normal; display: block; margin-top: 0px+dark: color: rgb(255, 255, 255); background-color: rgba(0, 0, 0, 0); color-scheme: normal; font-size: 16px; line-height: normal; display: block; margin-top: 0px+light dark: color: rgb(0, 0, 0); background-color: rgba(0, 0, 0, 0); color-scheme: normal; font-size: 16px; line-height: normal; display: block; margin-top: 0px+no-quirks again: color: rgb(0, 0, 0); background-color: rgba(0, 0, 0, 0); color-scheme: normal; font-size: 16px; line-height: normal; display: block; margin-top: 0px+no-quirks after one went: color: rgb(0, 0, 0); background-color: rgba(0, 0, 0, 0); color-scheme: normal; font-size: 16px; line-height: normal; display: block; margin-top: 0px+dark after one went: color: rgb(255, 255, 255); background-color: rgba(0, 0, 0, 0); color-scheme: normal; font-size: 16px; line-height: normal; display: block; margin-top: 0pxdiff --git a/Tests/LibWeb/Text/input/css/style-engine/initial-style-across-documents.html b/Tests/LibWeb/Text/input/css/style-engine/initial-style-across-documents.htmlnew file mode 100644index 00000000000..caf53da8cca--- /dev/null+++ b/Tests/LibWeb/Text/input/css/style-engine/initial-style-across-documents.html@@ -0,0 +1,40 @@+<!doctype html>+<script src="../../include.js"></script>+<body>+<script>+ // Documents of one process share the initial groups they compute alike. Each of these documents reads the initial+ // values its own inputs give it, in whichever order the documents take them.+ const documents = {+ "no-quirks": "<!doctype html><div id=target>x</div>",+ "quirks": "<div id=target>x</div>",+ "dark": `<!doctype html><meta name="color-scheme" content="dark"><div id=target>x</div>`,+ "light dark": `<!doctype html><meta name="color-scheme" content="light dark"><div id=target>x</div>`,+ "no-quirks again": "<!doctype html><div id=target>x</div>",+ };+ const properties = ["color", "background-color", "color-scheme", "font-size", "line-height", "display", "margin-top"];++ function describe(frame) {+ const target = frame.contentDocument.getElementById("target");+ const style = frame.contentWindow.getComputedStyle(target);+ return properties.map(property => `${property}: ${style.getPropertyValue(property)}`).join("; ");+ }++ asyncTest(async done => {+ const frames = [];+ for (const [name, html] of Object.entries(documents)) {+ const frame = document.createElement("iframe");+ frame.srcdoc = html;+ const loaded = new Promise(resolve => (frame.onload = resolve));+ document.body.append(frame);+ await loaded;+ println(`${name}: ${describe(frame)}`);+ frames.push(frame);+ }+ // The documents that came first keep their values with the others around, and one that goes leaves them.+ frames[1].remove();+ println(`no-quirks after one went: ${describe(frames[0])}`);+ println(`dark after one went: ${describe(frames[2])}`);+ document.body.innerHTML = "";+ done();+ });+</script>