Truly independent web browser
LibWeb: Keep the style records of elements out of the content table
Andreas Kling08d899efbec2
diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex 4e7f8fcdd68..44d9edaaa03 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -2780,6 +2780,11 @@ u64 Internals::style_record_identity(DOM::Element& element)return element.style_record_identity().value();}+u64 Internals::custom_property_environment_identity(DOM::Element& element)+{+ return element.installed_style().custom_property_environment();+}+u64 Internals::layout_style_record_identity(DOM::Element& element){Layout::ForcedReadScope read { element.document() };diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.hindex 6d86656f4be..5bdc6fd182a 100644--- a/Libraries/LibWeb/Internals/Internals.h+++ b/Libraries/LibWeb/Internals/Internals.h@@ -318,6 +318,7 @@ public:GC::Ref<JS::Object> style_memory_report();u64 style_memory_of_frames();u64 style_record_identity(DOM::Element&);+ u64 custom_property_environment_identity(DOM::Element&);u64 layout_style_record_identity(DOM::Element&);u64 before_style_record_identity(DOM::Element&);u64 before_layout_style_record_identity(DOM::Element&);diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idlindex 55778e3f747..555bf965c16 100644--- a/Libraries/LibWeb/Internals/Internals.idl+++ b/Libraries/LibWeb/Internals/Internals.idl@@ -387,6 +387,7 @@ interface Internals {// once however many of them share it.unsigned long long styleMemoryOfFrames();unsigned long long styleRecordIdentity(Element element);+ unsigned long long customPropertyEnvironmentIdentity(Element element);unsigned long long layoutStyleRecordIdentity(Element element);unsigned long long beforeStyleRecordIdentity(Element element);unsigned long long beforeLayoutStyleRecordIdentity(Element element);diff --git a/Libraries/LibWeb/Rust/src/css/style/computed.rs b/Libraries/LibWeb/Rust/src/css/style/computed.rsindex c72c9dcaf8c..cd3e5fdd28d 100644--- a/Libraries/LibWeb/Rust/src/css/style/computed.rs+++ b/Libraries/LibWeb/Rust/src/css/style/computed.rs@@ -1028,6 +1028,16 @@ impl ComputedGroupSets {FinalStyleRecordID::installed(self.installed.install(record, dependency_flags))}+ /// Take a slot for a record derived for what no element is, or answer one holding the same.+ /// `dependency_flags` says what the view of a record in a new slot depends on.+ pub(super) fn install_derived_record(+ &mut self,+ record: &std::sync::Arc<super::pipeline::Record>,+ dependency_flags: impl FnOnce() -> u8,+ ) -> FinalStyleRecordID {+ FinalStyleRecordID::installed(self.installed.install_derived(record, dependency_flags))+ }+/// The identity `record` holds already, if it holds one.pub(super) fn installed_record_named_by(&self,@@ -1036,15 +1046,6 @@ impl ComputedGroupSets {self.installed.named_by(record).map(FinalStyleRecordID::installed)}- /// An installed record holding the style `record` does, which an element computing `record`- /// holds in its place.- pub(super) fn installed_record_holding_the_same_style_as(- &self,- record: &super::pipeline::Record,- ) -> Option<&std::sync::Arc<super::pipeline::Record>> {- self.installed.holding_the_same_style_as(record)- }-/// The record the engine computed that the installed `record` installs, where it is one.pub(super) fn installed_record(&self,@@ -1853,7 +1854,7 @@ mod tests {pseudo_element_styles,)).with_test_dependency_flags(dependency_flags);- sets.install_record(&record, || 0)+ sets.install_derived_record(&record, || 0)}/// Assigns `target` a record installed as [`install`] installs it.diff --git a/Libraries/LibWeb/Rust/src/css/style/installed_records.rs b/Libraries/LibWeb/Rust/src/css/style/installed_records.rsindex f701ef05c7b..f56732b74c8 100644--- a/Libraries/LibWeb/Rust/src/css/style/installed_records.rs+++ b/Libraries/LibWeb/Rust/src/css/style/installed_records.rs@@ -17,12 +17,10 @@//! the other named after the fork, the name means nothing to it: it installs a copy of the record,//! and the name is told from one of its own by whether its slot holds the record.//!-//! Records that hold the same values share a slot, as the host builds what it renders from once-//! per identity. They are found by their longhand table's slot hash sum, which the table keeps as-//! it is written, and told apart by comparing what they hold.-//! A record a pass computes that holds what an installed one does gives way to the installed one-//! before it is installed, so that elements computing the same style, such as the clones of a-//! subtree, hold one record, and their children are computed from it.+//! An element holds the record it computed. The records of styles derived for what no element is, as+//! the anonymous boxes of a layout tree and the samples of animations, that hold the same values share+//! a slot: there is one of them per box, which nothing shares before they are made. They are found+//! by a hash of the longhands styles most often differ in, and told apart by comparing what they hold.use super::fast_hash::FastSet as HashSet;use super::pipeline::Record;@@ -94,11 +92,6 @@ impl InstalledRecord {pub(super) fn dependency_flags(&self) -> u8 {self.record.view_dependency_flags()}-- /// The key the slot is found under by what its record holds.- fn content_key(&self) -> u64 {- InstalledRecords::content_key(self.record())- }}/// The slots of the installed records.@@ -107,8 +100,8 @@ pub(super) struct InstalledRecords {slots: Vec<Option<InstalledRecord>>,generations: Vec<u32>,free: Vec<InstalledRecordSlot>,- /// The slots by the key of what their records hold, which each slot's record keeps.- by_content: hashbrown::HashTable<InstalledRecordSlot>,+ /// The slots of the records derived for what no element is, by the key of what they hold.+ derived_by_content: hashbrown::HashTable<InstalledRecordSlot>,/// The records whose last holder let go, which the next sweep frees unless one took them again.released: Vec<InstalledRecordID>,/// How many leases on the records held as they are taken were taken.@@ -128,7 +121,10 @@ impl InstalledRecords {vec_bytes(&self.slots)+ vec_bytes(&self.generations)+ vec_bytes(&self.free)- + crate::heap_size::hash_table_bytes(self.by_content.capacity(), size_of::<InstalledRecordSlot>())+ + crate::heap_size::hash_table_bytes(+ self.derived_by_content.capacity(),+ size_of::<InstalledRecordSlot>(),+ )+ vec_bytes(&self.released),);}@@ -140,24 +136,13 @@ impl InstalledRecords {self.slots[id.slot.index()].as_ref()}- /// The identity `record` is installed under: that of the slot holding it, that of a slot- /// holding the same values, or a new slot, which the record names, or a copy of it where a- /// fork's slot names it already. `dependency_flags` says what a new slot's view depends on.+ /// The identity `record` is installed under: that of the slot holding it, or a new slot, which+ /// the record names, or a copy of it where a fork's slot names it already. `dependency_flags`+ /// says what a new slot's view depends on.pub(super) fn install(&mut self, record: &Arc<Record>, dependency_flags: impl FnOnce() -> u8) -> InstalledRecordID {if let Some(id) = self.named_by(record) {return id;}- let content_key = Self::content_key(record);- if let Some(&slot) = self.by_content.find(content_key, |&slot| {- self.slots[slot.index()]- .as_ref()- .is_some_and(|entry| entry.record().holds_the_same_as(record))- }) {- return InstalledRecordID {- slot,- generation: self.generations[slot.index()],- };- }let id = match self.free.pop() {Some(slot) => InstalledRecordID {slot,@@ -189,21 +174,47 @@ impl InstalledRecords {holders: 0,released_in: self.lease_epoch,});- let slots = &self.slots;- self.by_content.insert_unique(content_key, id.slot, |slot| {- slots[slot.index()]- .as_ref()- .expect("an indexed slot holds its record")- .content_key()- });// NB: A slot nothing holds yet is freed by the next sweep unless an assignment takes it.self.released.push(id);id}- /// The key a slot for `record` is found under by what the record holds: the- /// content hashes of the values of the longhands styles most often differ in, which records- /// holding the same values hash alike.+ /// The identity the record `record`, derived for what no element is, is installed under: that of a slot holding+ /// the same, or a new slot as [`Self::install`] takes.+ pub(super) fn install_derived(+ &mut self,+ record: &Arc<Record>,+ dependency_flags: impl FnOnce() -> u8,+ ) -> InstalledRecordID {+ if let Some(id) = self.named_by(record) {+ return id;+ }+ let content_key = Self::content_key(record);+ if let Some(&slot) = self.derived_by_content.find(content_key, |&slot| {+ self.slots[slot.index()]+ .as_ref()+ .is_some_and(|entry| entry.record().holds_the_same_as(record))+ }) {+ return InstalledRecordID {+ slot,+ generation: self.generations[slot.index()],+ };+ }+ let id = self.install(record, dependency_flags);+ let slots = &self.slots;+ self.derived_by_content.insert_unique(content_key, id.slot, |slot| {+ Self::content_key(+ slots[slot.index()]+ .as_ref()+ .expect("an indexed slot holds its record")+ .record(),+ )+ });+ id+ }++ /// The key a record is found under by what it holds: the content hashes of the values of the longhands styles most+ /// often differ in, which records holding the same values hash alike.fn content_key(record: &Record) -> u64 {use crate::css::computed_values::LonghandID;use crate::css::property_metadata::property_id as prop;@@ -230,16 +241,6 @@ impl InstalledRecords {hasher.finish()}- /// An installed record holding the style `record` does, whatever pseudo-elements either styles.- pub(super) fn holding_the_same_style_as(&self, record: &Record) -> Option<&Arc<Record>> {- let slot = self.by_content.find(Self::content_key(record), |&slot| {- self.slots[slot.index()]- .as_ref()- .is_some_and(|entry| entry.record().holds_the_same_style_as(record))- })?;- Some(self.slots[slot.index()].as_ref()?.record())- }-/// The identity of the slot holding `record`, where one here does. A record can name a slot of/// a fork instead, which here is free or holds another record.pub(super) fn named_by(&self, record: &Arc<Record>) -> Option<InstalledRecordID> {@@ -316,9 +317,6 @@ impl InstalledRecords {}let entry = self.slots[index].take().expect("a released slot holds its record");entry.record().forget_installed_record();- if let Ok(indexed) = self.by_content.find_entry(entry.content_key(), |&slot| slot == id.slot) {- indexed.remove();- }// NB: A slot whose generations ran out is never taken again.if self.generations[index] < InstalledRecordID::MAX_GENERATION {self.generations[index] += 1;@@ -328,6 +326,10 @@ impl InstalledRecords {false});self.released = released;+ if freed != 0 {+ let slots = &self.slots;+ self.derived_by_content.retain(|slot| slots[slot.index()].is_some());+ }freed}@@ -368,7 +370,6 @@ mod tests {assert!(!Arc::ptr_eq(©, &shared));assert!(copy.holds_the_same_as(&shared));assert_eq!(original.named_by(©), Some(here));- assert_eq!(original.install(&shared, || 0), here);}#[test]diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/install.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/install.rsindex 11fbcca5238..dbfeb0e91ea 100644--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/install.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/install.rs@@ -220,7 +220,7 @@ impl StyleInstallation {impl RetainedState {/// The identity `record` is installed under: the one it names, the one another element took- /// for it in this installation, kept in `installed`, or a new one.+ /// for a copy of it in this installation, kept in `installed`, or a new one.#[expect(clippy::mutable_key_type,reason = "a key hashes and compares only the address it holds"@@ -240,7 +240,10 @@ impl RetainedState {let id = records.install_record(record, || {computed::record_dependency_flags(&record.facts(), &record.payloads)});- installed.insert(PointerKey::new(record, ()), id);+ // NB: A record a fork's slot names took a copy in this slot, which it finds again here.+ if records.installed_record_named_by(record).is_none() {+ installed.insert(PointerKey::new(record, ()), id);+ }id}@@ -301,9 +304,8 @@ impl RetainedState {|| parent.is_some_and(|parent| self.hidden_before(parent, scratch));scratch.note_hidden_before(node, below_display_none || self.record_is_display_none(old));let new_record = self.install_record(record, &mut scratch.installed);- // NB: Where the record holds what one installed before it does, or the element installs a copy of it in- // another custom property environment, the element keeps what it installed, and its own goes: the- // composition of its animations lies over what it holds.+ // NB: Where the element installs a copy of the record, as in another custom property environment, the element+ // keeps what it installed, and its own goes: the composition of its animations lies over what it holds.if let Some(installed) = self.computed_group_sets.installed_record(new_record)&& !Arc::ptr_eq(installed, computed_record){diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/install_scratch.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/install_scratch.rsindex fa499f7581a..22c701c5414 100644--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/install_scratch.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/install_scratch.rs@@ -43,8 +43,8 @@ pub(super) struct InstallScratch {pub(super) installed: HashMap<PointerKey<std::sync::Arc<super::Record>>, computed::FinalStyleRecordID>,/// The elements the installation let go of the animation overlay of, with its view.pub(super) released_compositions: Vec<(StyleNodeID, super::live::HeldComposition)>,- /// The elements whose records hold what a record installed before them does, which they keep- /// in place of their own, by the address of their own.+ /// The elements that installed a copy of their records, which they keep in place of their own,+ /// by the address of their own.pub(super) adopted: Vec<(StyleNodeID, usize, std::sync::Arc<super::Record>)>,}@@ -188,25 +188,6 @@ mod tests {(engine, nodes)}- #[test]- fn an_element_whose_record_holds_what_an_installed_one_does_keeps_that_one() {- let (mut engine, nodes) = linear_document();- let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);- add_rules(- &mut engine,- sheet,- ".a { color: rgb(0, 128, 0); } .b { color: rgb(0, 128, 0); }",- );- start_live(&mut engine, nodes[0]);- add_class(&mut engine, nodes[1], "a");- add_class(&mut engine, nodes[2], "b");- run_style_update(&mut engine, nodes[0]);- assert!(std::sync::Arc::ptr_eq(- &live_record(&engine, nodes[1]),- &live_record(&engine, nodes[2])- ));- }-#[test]fn orders_each_live_element_once_in_tree_order() {let (engine, nodes) = document_with_a_late_first_child();diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/records.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/records.rsindex a608d29c631..9c4bd5dfe5a 100644--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/records.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/records.rs@@ -1051,7 +1051,7 @@ impl RetainedState {}fn install_new_record(&mut self, record: Arc<Record>) -> computed::FinalStyleRecordID {- self.computed_group_sets.install_record(&record, || {+ self.computed_group_sets.install_derived_record(&record, || {computed::record_dependency_flags(&record.facts(), &record.payloads)})}@@ -1779,6 +1779,26 @@ impl<'a> Records<'a> {Some(self.state.custom_property_environments.store(sampled))}+ /// The record `node` held before this pass, or the one the host holds for it or composes its animations over, where+ /// it holds the style `record` does: what it keeps in place of `record`, so that its children compute from it as+ /// they did, and the host has nothing to take.+ pub(super) fn held_before_holding_the_same_style_as(+ &self,+ node: StyleNodeID,+ record: &Record,+ ) -> Option<&'a Arc<Record>> {+ let previous = self.previous?.get(node);+ let held = self+ .state+ .held_style_records+ .get(node)+ .map(|held| held.sample_of_animations().map_or(held, |sample| &sample.base));+ previous+ .into_iter()+ .chain(held.filter(|held| previous.is_none_or(|previous| !Arc::ptr_eq(previous, held))))+ .find(|candidate| candidate.holds_the_same_style_as(record))+ }+/// Whether this pass computed `node`.pub(super) fn computed(&self, node: StyleNodeID) -> bool {self.cells.held(node.element_slot()).is_some()diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal.rsindex d951893ef37..f8badfa93ea 100644--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal.rs@@ -1903,13 +1903,10 @@ impl<'a> Scratch<'a> {).with_custom_properties(custom_properties.as_ref()),});- // NB: An element computing what an installed record holds, as the clone of an element does,- // holds that record: installing it takes the slot the record names, and the children of- // the element are computed from the record the children of the original were.self.last_record = Some(record.clone());- let record = state- .computed_group_sets- .installed_record_holding_the_same_style_as(&record)+ let record = context+ .records+ .held_before_holding_the_same_style_as(node, &record).cloned().unwrap_or(record);// Only what the key and the conditions of an entry name is read of what may differ betweendiff --git a/Libraries/LibWeb/Rust/src/css/style/publication.rs b/Libraries/LibWeb/Rust/src/css/style/publication.rsindex e8b4895d3b3..e729d78979f 100644--- a/Libraries/LibWeb/Rust/src/css/style/publication.rs+++ b/Libraries/LibWeb/Rust/src/css/style/publication.rs@@ -532,7 +532,7 @@ impl RetainedState {.unwrap_or_else(|| self.default_groups().groups().clone());let record = std::sync::Arc::new(super::pipeline::Record::derived(&source, &payloads)).with_pseudo_element_styles(super::pipeline::PseudoElementStyles::from_bits(pseudo_element_styles));- let identity = self.computed_group_sets.install_record(&record, || {+ let identity = self.computed_group_sets.install_derived_record(&record, || {computed::record_dependency_flags(&record.facts(), &record.payloads)});match target.is_pseudo() {diff --git a/Tests/LibWeb/Text/expected/css/style-engine/counter-style-consumers-per-scope.txt b/Tests/LibWeb/Text/expected/css/style-engine/counter-style-consumers-per-scope.txtnew file mode 100644index 00000000000..73a7de26ed1--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-engine/counter-style-consumers-per-scope.txt@@ -0,0 +1,4 @@+scopes' consumers hold different records: true+first scope's consumers look alike: true+second scope's consumers look alike: true+each scope's consumers use its counter style: truediff --git a/Tests/LibWeb/Text/expected/css/style-engine/counter-style-records-shared-per-scope.txt b/Tests/LibWeb/Text/expected/css/style-engine/counter-style-records-shared-per-scope.txtdeleted file mode 100644index dc2bb22bc8d..00000000000--- a/Tests/LibWeb/Text/expected/css/style-engine/counter-style-records-shared-per-scope.txt+++ /dev/null@@ -1,5 +0,0 @@-first scope's consumers share a record: true-second scope's consumers share a record: true-scopes' consumers hold different records: true-non-consumers share a record across scopes: true-each scope's consumers use its counter style: truediff --git a/Tests/LibWeb/Text/input/css/style-engine/counter-style-records-shared-per-scope.html b/Tests/LibWeb/Text/input/css/style-engine/counter-style-consumers-per-scope.htmlsimilarity index 62%rename from Tests/LibWeb/Text/input/css/style-engine/counter-style-records-shared-per-scope.htmlrename to Tests/LibWeb/Text/input/css/style-engine/counter-style-consumers-per-scope.htmlindex 37e70b3e07a..dc2ea67cffd 100644--- a/Tests/LibWeb/Text/input/css/style-engine/counter-style-records-shared-per-scope.html+++ b/Tests/LibWeb/Text/input/css/style-engine/counter-style-consumers-per-scope.html@@ -29,15 +29,12 @@const second = append_items(second_root);internals.updateStyle();const record = element => internals.styleRecordIdentity(element);- // The consumers of one scope's counter style share a record, as do their markers, and- // neither answers for a consumer of the other scope's; an element naming no counter style- // shares its record across scopes.- println(`first scope's consumers share a record: ${first.every(item => record(item) === record(first[0]))}`);- println(`second scope's consumers share a record: ${second.every(item => record(item) === record(second[0]))}`);- println(`scopes' consumers hold different records: ${record(first[0]) !== record(second[0])}`);- const plain = root => root.querySelector("span");- println(`non-consumers share a record across scopes: ${record(plain(first_root)) === record(plain(second_root))}`);const width = element => element.getBoundingClientRect().width;- println(`each scope's consumers use its counter style: ${width(second[0]) > width(first[0])}`);+ // NB: Whether two consumers of one scope's counter style hold one record is up to the caches, which may have no+ // room for it. No record answers for a consumer of the other scope's, and each consumer shows its own.+ println(`scopes' consumers hold different records: ${first.every(a => second.every(b => record(a) !== record(b)))}`);+ println(`first scope's consumers look alike: ${first.every(item => width(item) === width(first[0]))}`);+ println(`second scope's consumers look alike: ${second.every(item => width(item) === width(second[0]))}`);+ println(`each scope's consumers use its counter style: ${first.every(a => second.every(b => width(b) > width(a)))}`);});</script>diff --git a/Tests/LibWeb/Text/input/css/style-engine/inheritable-custom-property-environment-identity.html b/Tests/LibWeb/Text/input/css/style-engine/inheritable-custom-property-environment-identity.htmlindex 0ab31c8e5e0..da8cdb4934e 100644--- a/Tests/LibWeb/Text/input/css/style-engine/inheritable-custom-property-environment-identity.html+++ b/Tests/LibWeb/Text/input/css/style-engine/inheritable-custom-property-environment-identity.html@@ -15,7 +15,7 @@ test(() => {root.style.setProperty(`--inherited-${index}`, index);root.style.setProperty('--number', '1', 'important');internals.updateStyle();- println(`same child environment: ${internals.styleRecordIdentity(first) === internals.styleRecordIdentity(second)}`);+ println(`same child environment: ${internals.customPropertyEnvironmentIdentity(first) === internals.customPropertyEnvironmentIdentity(second)}`);println(`inherited value: ${getComputedStyle(first).getPropertyValue('--inherited-15')}`);const animation = first.animate({'--number': ['2', '4']}, {duration: 1000, fill: 'both'});