Truly independent web browser
LibWeb: Read through functions for an animated custom property cycle
Andreas Kling4acc1b203ce7
diff --git a/Libraries/LibWeb/Rust/src/css/custom_properties.rs b/Libraries/LibWeb/Rust/src/css/custom_properties.rsindex 007b0766f61..3ee45c7ea42 100644--- a/Libraries/LibWeb/Rust/src/css/custom_properties.rs+++ b/Libraries/LibWeb/Rust/src/css/custom_properties.rs@@ -12,6 +12,7 @@ use std::borrow::Cow;use std::cell::Cell;use std::cell::RefCell;use std::collections::HashMap;+use std::collections::HashSet;use std::ffi::c_void;use std::rc::Rc;use std::sync::Arc;@@ -476,6 +477,13 @@ impl CustomPropertyRegistry {}/// Whether the custom property `name` names is registered.+ /// Whether the name is registered with an initial value, which it reads as where nothing declares it.+ pub(crate) fn has_initial_value(&self, name: &Utf16FlyString) -> bool {+ self.registrations+ .get(name)+ .is_some_and(|registration| registration.initial_source.is_some())+ }+pub(crate) fn is_registered(&self, name: &Utf16FlyString) -> bool {self.registrations.contains_key(name)}@@ -1014,6 +1022,11 @@ impl CustomPropertyStore {Some(entry.value.pointer() as usize)}+ /// Whether the store, or one it inherits from, holds a value of the name.+ pub(crate) fn holds_name(&self, name: &Utf16FlyString) -> bool {+ self.get_by_name_with_owner(name).is_some()+ }+fn get_by_name_with_owner(&self, name: &Utf16FlyString) -> Option<(&CustomPropertyEntry, &CustomPropertyStore)> {self.own_values.get(&name.raw_identity())@@ -2844,6 +2857,151 @@ fn split_function_arguments(tokens: &[ComponentValue]) -> Vec<&[ComponentValue]>tokens.split(ComponentValue::is_comma).collect()}+/// The custom properties of the element that substituting `tokens` reads, looking through the custom functions it+/// calls as [`replace_a_dashed_function`] resolves them. A parameter or local of a function on the way shadows the+/// element's property of that name, and `holds_a_value` says of a name whether its `var()` leaves its fallback unread.+/// A function's reads are worked out once per number of arguments passed to it, so this takes time in proportion to+/// the functions and the calls, however many paths lead through them.+/// What `if()`, `attr()`, `inherit()` and `env()` read is left out: which of their arguments substitute depends on the+/// values themselves.+pub(crate) fn custom_property_reads_through_functions(+ tokens: &[ComponentValue],+ functions: &CustomFunctionRegistry<'_>,+ holds_a_value: &dyn Fn(&Utf16FlyString) -> bool,+) -> Vec<Arc<[u16]>> {+ let mut read_ahead = FunctionReadAhead {+ functions,+ holds_a_value,+ calling: Vec::new(),+ reads_of_calls: HashMap::new(),+ reads: HashSet::new(),+ };+ read_ahead.visit(tokens);+ read_ahead.reads.iter().map(|name| Arc::from(name.to_utf16())).collect()+}++struct FunctionReadAhead<'a, 'b> {+ functions: &'a CustomFunctionRegistry<'b>,+ holds_a_value: &'a dyn Fn(&Utf16FlyString) -> bool,+ /// The functions whose bodies are being visited, innermost last: their local scopes.+ calling: Vec<&'a PreparedCustomFunction<'b>>,+ /// What a call of a definition with so many of its parameters passed reads, past the locals of that definition and+ /// of what it calls. Which caller's locals shadow those is for each caller to say as it takes them.+ reads_of_calls: HashMap<(*const PreparedCustomFunction<'b>, usize), Rc<HashSet<Utf16FlyString>>>,+ /// What the innermost function being visited reads so far.+ reads: HashSet<Utf16FlyString>,+}++impl FunctionReadAhead<'_, '_> {+ fn visit(&mut self, tokens: &[ComponentValue]) {+ for value in tokens {+ match &value.kind {+ ComponentKind::Token(_) => {}+ ComponentKind::SimpleBlock { values, .. } => self.visit(values.as_ref()),+ ComponentKind::Function { name, values } => {+ if name.eq_ignore_ascii_case("var") {+ self.visit_var(values.as_ref());+ } else if name.starts_with_ascii("--") {+ self.visit_call(name.as_ref(), values.as_ref());+ } else if !is_substitution_function(name.as_ref()) {+ self.visit(values.as_ref());+ }+ }+ }+ }+ }++ fn visit_var(&mut self, arguments: &[ComponentValue]) {+ let comma = arguments.iter().position(ComponentValue::is_comma);+ let first_argument = trim_whitespace(&arguments[..comma.unwrap_or(arguments.len())]);+ let name = match first_argument {+ [value] => value.ident_string().filter(|name| name.starts_with_ascii("--")),+ _ => None,+ };+ let Some(name) = name else {+ self.visit(first_argument);+ return;+ };+ let fly_name = name.fly_string();+ if self+ .calling+ .last()+ .is_some_and(|function| function.declares_local(&fly_name))+ {+ return;+ }+ // NB: A fallback counts even where a caller's local shadows the name, which can leave that local no value.+ let reads_fallback = !(self.holds_a_value)(&fly_name);+ self.reads.insert(fly_name.into_owned());+ if let Some(comma) = comma+ && reads_fallback+ {+ self.visit(&arguments[comma + 1..]);+ }+ }++ fn visit_call(&mut self, name: &[u16], arguments: &[ComponentValue]) {+ let caller_scope_identity = self+ .calling+ .last()+ .map_or(self.functions.caller_scope_identity, |function| function.scope_identity);+ let functions = self.functions;+ let Some(function) = functions+ .visible+ .iter()+ .filter(|visibility| visibility.caller_scope_identity == caller_scope_identity)+ .map(|visibility| &functions.definitions[visibility.definition_index])+ .find(|definition| definition.signature.name.units() == name)+ else {+ return;+ };+ let arguments = split_function_arguments(arguments);+ for argument in &arguments {+ self.visit(argument);+ }+ // NB: A function reached again is a cycle of its own, and reads nothing it has not read on the way there.+ if self.calling.iter().any(|calling| calling.identity == function.identity) {+ return;+ }+ let passed = arguments.len().min(function.parameter_defaults.len());+ let key = (std::ptr::from_ref(function), passed);+ let reads_of_call = if let Some(reads_of_call) = self.reads_of_calls.get(&key) {+ Rc::clone(reads_of_call)+ } else {+ let reads_of_caller = std::mem::take(&mut self.reads);+ self.calling.push(function);+ for default_value in function.parameter_defaults[passed..].iter().flatten() {+ self.visit(default_value.as_ref());+ }+ // NB: Resolving function styles computes every declaration of the body, whether the result reads it or not.+ for declaration in &function.declarations {+ self.visit(declaration.tokens());+ }+ self.calling.pop();+ let reads_of_call = Rc::new(std::mem::replace(&mut self.reads, reads_of_caller));+ self.reads_of_calls.insert(key, Rc::clone(&reads_of_call));+ reads_of_call+ };+ let caller = self.calling.last().copied();+ self.reads.extend(+ reads_of_call+ .iter()+ .filter(|name| !caller.is_some_and(|caller| caller.declares_local(name)))+ .cloned(),+ );+ }+}++impl PreparedCustomFunction<'_> {+ fn declares_local(&self, name: &Utf16FlyString) -> bool {+ self.signature+ .parameters+ .iter()+ .any(|parameter| parameter.name == *name)+ || self.declarations.iter().any(|declaration| declaration.name == *name)+ }+}+// https://drafts.csswg.org/css-mixins/#resolve-function-stylesfn resolve_function_styles<'a, 'names>(store: Option<&CustomPropertyStore>,diff --git a/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs b/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rsindex c71805d2add..c088c4c26e5 100644--- a/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs+++ b/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs@@ -755,15 +755,17 @@ impl RetainedState {/// The custom properties in a dependency cycle through what an element's animations declare, as/// `--p: var(--q)` in a keyframe beside `--q: var(--p)` on the element. An animated value wins- /// the cascade over a declared one, so a name it animates reads as its keyframes do.+ /// the cascade over a declared one, so a name it animates reads as its keyframes do. `inherited`+ /// is the environment the element inherits.pub(crate) fn custom_properties_in_an_animated_cycle(&self,node: StyleNodeID,pseudo: Option<u8>,+ inherited: Option<&CustomPropertyStore>,) -> Vec<crate::css::retained_fly_string::RetainedUtf16FlyString> {type Name = crate::css::retained_fly_string::RetainedUtf16FlyString;let slot = pseudo.map_or(0, |kind| kind + 1);- let mut reads: Vec<(Name, Vec<Arc<[u16]>>)> = Vec::new();+ let mut written: Vec<(Name, &StyleValueData)> = Vec::new();for effect in self.element_animation_effects(node, slot) {for keyframe in effect.keyframes() {for declaration in effect.custom_declarations_of(keyframe) {@@ -771,23 +773,22 @@ impl RetainedState {else {continue;};- let names = named_custom_property_reads(value.data()).unwrap_or_default();- let names = names.into_iter().map(Arc::from);- match reads.iter_mut().find(|(name, _)| *name == declaration.name) {- Some((_, read)) => read.extend(names),- None => reads.push((declaration.name.clone(), names.collect())),- }+ written.push((declaration.name.clone(), value.data()));}}}- if reads.iter().all(|(_, read)| read.is_empty()) {+ if written.iter().all(|(_, value)| {+ !value_calls_custom_functions(value)+ && named_custom_property_reads(value).is_none_or(|names| names.is_empty())+ }) {return Vec::new();}- if let Some(declarations) = self+ let animated_count = written.len();+ let declarations = self.live_style.as_ref()- .and_then(|live| live.custom_declarations_of(node, pseudo))- {+ .and_then(|live| live.custom_declarations_of(node, pseudo));+ if let Some(declarations) = &declarations {for (declared, value) in declarations.iter().filter(|(declared, _)| declared.operator() == CascadeOperator::Declared)@@ -796,12 +797,44 @@ impl RetainedState {continue;};let name = Name::from_utf16(name.to_utf16().as_ref());- if reads.iter().all(|(animated, _)| *animated != name) {- let names = named_custom_property_reads(value.data()).unwrap_or_default();- reads.push((name, names.into_iter().map(Arc::from).collect()));+ if written[..animated_count].iter().all(|(animated, _)| *animated != name) {+ written.push((name, value.data()));}}}+ // NB: A container condition the engine cannot decide leaves what a function reads unknown, as a read of no name.+ let functions = written+ .iter()+ .any(|(_, value)| value_calls_custom_functions(value))+ .then(|| self.prepare_custom_functions(&self.document_functions, node, pseudo))+ .flatten();+ let registry = self.document_style_computation_inputs.custom_property_registry();+ let holds_a_value = |name: &ak::Utf16FlyString| {+ written.iter().any(|(written, _)| written.raw() == name.raw_identity())+ || registry.has_initial_value(name)+ || inherited.is_some_and(|store| store.holds_name(name))+ };+ let mut reads: Vec<(Name, Vec<Arc<[u16]>>)> = Vec::new();+ for (name, value) in &written {+ let names: Vec<Arc<[u16]>> = match (&functions, substituted_tokens(value)) {+ (Some(functions), StyleValueData::Unresolved(unresolved)) if value_calls_custom_functions(value) => {+ crate::css::custom_properties::custom_property_reads_through_functions(+ unresolved.components().as_ref(),+ &functions.registry,+ &holds_a_value,+ )+ }+ _ => named_custom_property_reads(value)+ .unwrap_or_default()+ .into_iter()+ .map(Arc::from)+ .collect(),+ };+ match reads.iter_mut().find(|(read_name, _)| read_name == name) {+ Some((_, read)) => read.extend(names),+ None => reads.push((name.clone(), names)),+ }+ }let reads_of = |name: &[u16]| {reads.iter()diff --git a/Libraries/LibWeb/Rust/src/css/style_compute.rs b/Libraries/LibWeb/Rust/src/css/style_compute.rsindex 3fac1cde38a..eb704955801 100644--- a/Libraries/LibWeb/Rust/src/css/style_compute.rs+++ b/Libraries/LibWeb/Rust/src/css/style_compute.rs@@ -8304,15 +8304,15 @@ fn finish_animation_sample(// looked at here, since each pass only substitutes the values the last one left.let cycle_pseudo =(input.pseudo_kind != crate::css::cascaded_properties::NO_PSEUDO_ELEMENT).then_some(input.pseudo_kind);- for name in engine.custom_properties_in_an_animated_cycle(node, cycle_pseudo) {- // SAFETY: The stores are null or live for the sample.- let inherited = unsafe {- input- .stores- .inheritance- .cast::<crate::css::custom_properties::CustomPropertyStore>()- .as_ref()- };+ // SAFETY: The stores are null or live for the sample.+ let inherited = unsafe {+ input+ .stores+ .inheritance+ .cast::<crate::css::custom_properties::CustomPropertyStore>()+ .as_ref()+ };+ for name in engine.custom_properties_in_an_animated_cycle(node, cycle_pseudo, inherited) {let value = registry.invalid_at_computed_value_time(&name, inherited);match retained.iter_mut().find(|(animated, _)| *animated == name) {Some((_, animated)) => *animated = value,diff --git a/Tests/LibWeb/Text/expected/css/custom-property-animated-cycle-through-custom-function.txt b/Tests/LibWeb/Text/expected/css/custom-property-animated-cycle-through-custom-function.txtnew file mode 100644index 00000000000..075d205ab3a--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/custom-property-animated-cycle-through-custom-function.txt@@ -0,0 +1,12 @@+a function reads the other property: --p: 0px, --q: 0px+a function reads it through another: --p: 0px, --q: 0px+a local shadows it: --p: 2px, --q: 2px+a parameter shadows it: --p: 3px, --q: 3px+an argument reads it: --p: 0px, --q: 0px+a local nothing reads reads it: --p: 0px, --q: 0px+a fallback that is not used reads it: --p: 5px, --q: 5px+a fallback that is used reads it: --p: 0px, --q: 0px+a parameter's default reads it: --p: 0px, --q: 0px+a passed parameter's default reads it: --p: 6px, --q: 6px+a caller's local shadows it: --p: 4px, --q: 4px+a function calls itself: --p: 0px, --q: 0pxdiff --git a/Tests/LibWeb/Text/expected/css/custom-property-animated-cycle-through-many-function-paths.txt b/Tests/LibWeb/Text/expected/css/custom-property-animated-cycle-through-many-function-paths.txtnew file mode 100644index 00000000000..81b132cf33e--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/custom-property-animated-cycle-through-many-function-paths.txt@@ -0,0 +1,7 @@+every path through a chain leads to it: --p: 0px, --q: 0px+each call's local shadows it: --p: 2px, --q: 2px+a local shadows it, then a call reads it: --p: 0px, --q: 0px+a call reads it, then a local shadows it: --p: 0px, --q: 0px+each call passes the parameter: --p: 11px, --q: 11px+a call passes the parameter, then one leaves it out: --p: 0px, --q: 0px+a call leaves the parameter out, then one passes it: --p: 0px, --q: 0pxdiff --git a/Tests/LibWeb/Text/input/css/custom-property-animated-cycle-through-custom-function.html b/Tests/LibWeb/Text/input/css/custom-property-animated-cycle-through-custom-function.htmlnew file mode 100644index 00000000000..5618e6e8e3f--- /dev/null+++ b/Tests/LibWeb/Text/input/css/custom-property-animated-cycle-through-custom-function.html@@ -0,0 +1,77 @@+<!DOCTYPE html>+<style>+@property --p { syntax: "<length>"; inherits: true; initial-value: 0px; }+@property --q { syntax: "<length>"; inherits: true; initial-value: 0px; }+@property --held { syntax: "<length>"; inherits: true; initial-value: 4px; }+@function --read() { result: var(--q); }+@function --nested() { result: --read(); }+@function --local() { --q: 1px; result: var(--q); }+@function --parameter(--q: 2px) { result: var(--q); }+@function --pass(--value) { result: var(--value); }+@function --unused-local() { --unused: var(--q); result: 1px; }+@function --held-fallback() { result: var(--held, var(--q)); }+@function --unset-fallback() { result: var(--unset, var(--q)); }+@function --default(--value: var(--q)) { result: var(--value); }+@function --caller-local() { --q: 3px; result: --read(); }+@function --recursive() { result: --recursive(); }+</style>+<body>+<script src="../include.js"></script>+<script>+ asyncTest(async done => {+ // A keyframe's value takes part in a cycle exactly as the same value declared on the element does.+ const cases = {+ "a function reads the other property": "calc(--read() + 1px)",+ "a function reads it through another": "calc(--nested() + 1px)",+ "a local shadows it": "calc(--local() + 1px)",+ "a parameter shadows it": "calc(--parameter() + 1px)",+ "an argument reads it": "calc(--pass(var(--q)) + 1px)",+ "a local nothing reads reads it": "calc(--unused-local() + 1px)",+ "a fallback that is not used reads it": "calc(--held-fallback() + 1px)",+ "a fallback that is used reads it": "calc(--unset-fallback() + 1px)",+ "a parameter's default reads it": "calc(--default() + 1px)",+ "a passed parameter's default reads it": "calc(--default(5px) + 1px)",+ "a caller's local shadows it": "calc(--caller-local() + 1px)",+ "a function calls itself": "--recursive()",+ };++ let css = "";+ const elements = [];+ Object.entries(cases).forEach(([name, value], index) => {+ css += `.declared${index} { --p: ${value}; --q: var(--p); }\n`;+ css += `@keyframes k${index} { from, to { --p: ${value}; } }\n`;+ css += `.paused${index} { --q: var(--p); animation: k${index} 100s paused; }\n`;+ css += `.running${index} { --q: var(--p); animation: k${index} 100s linear; }\n`;+ const add = variant => {+ const element = document.createElement("div");+ element.className = `${variant}${index}`;+ document.body.append(element);+ return element;+ };+ elements.push({ name, declared: add("declared"), paused: add("paused"), running: add("running") });+ });+ const style = document.createElement("style");+ style.textContent = css;+ document.head.append(style);++ const values = element => {+ const style = getComputedStyle(element);+ return `--p: ${style.getPropertyValue("--p")}, --q: ${style.getPropertyValue("--q")}`;+ };+ elements.forEach(({ paused, running }) => {+ values(paused);+ values(running);+ });+ await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));+ await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));++ for (const { name, declared, paused, running } of elements) {+ println(`${name}: ${values(declared)}`);+ if (values(paused) !== values(declared))+ println(` paused differs: ${values(paused)}`);+ if (values(running) !== values(declared))+ println(` running differs: ${values(running)}`);+ }+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/custom-property-animated-cycle-through-many-function-paths.html b/Tests/LibWeb/Text/input/css/custom-property-animated-cycle-through-many-function-paths.htmlnew file mode 100644index 00000000000..ef59966017b--- /dev/null+++ b/Tests/LibWeb/Text/input/css/custom-property-animated-cycle-through-many-function-paths.html@@ -0,0 +1,68 @@+<!DOCTYPE html>+<style>+@property --p { syntax: "<length>"; inherits: true; initial-value: 0px; }+@property --q { syntax: "<length>"; inherits: true; initial-value: 0px; }+@function --read() { result: var(--q); }+@function --shadow() { --q: 1px; result: --read(); }+@function --shadow-twice() { result: calc(--shadow() + --shadow()); }+@function --shadow-then-read() { result: calc(--shadow() + --read()); }+@function --read-then-shadow() { result: calc(--read() + --shadow()); }+@function --default(--value: var(--q)) { result: var(--value); }+@function --passed-twice() { result: calc(--default(5px) + --default(6px)); }+@function --passed-then-left-out() { result: calc(--default(5px) + --default()); }+@function --left-out-then-passed() { result: calc(--default() + --default(5px)); }+</style>+<body>+<script src="../include.js"></script>+<script>+ asyncTest(async done => {+ // A chain of functions that each call the next twice has twice as many paths at each level.+ const depth = 40;+ let css = "";+ for (let level = 0; level < depth; ++level)+ css += `@function --chain${level}() { result: calc(--chain${level + 1}() + --chain${level + 1}()); }\n`;+ css += `@function --chain${depth}() { result: var(--q); }\n`;++ // A function's reads depend on who calls it and on what the call passes, in whichever order the calls come.+ const cases = {+ "every path through a chain leads to it": "--chain0()",+ "each call's local shadows it": "--shadow-twice()",+ "a local shadows it, then a call reads it": "--shadow-then-read()",+ "a call reads it, then a local shadows it": "--read-then-shadow()",+ "each call passes the parameter": "--passed-twice()",+ "a call passes the parameter, then one leaves it out": "--passed-then-left-out()",+ "a call leaves the parameter out, then one passes it": "--left-out-then-passed()",+ };++ const elements = [];+ Object.entries(cases).forEach(([name, value], index) => {+ css += `.declared${index} { --p: ${value}; --q: var(--p); }\n`;+ css += `@keyframes k${index} { from, to { --p: ${value}; } }\n`;+ css += `.paused${index} { --q: var(--p); animation: k${index} 100s paused; }\n`;+ const add = variant => {+ const element = document.createElement("div");+ element.className = `${variant}${index}`;+ document.body.append(element);+ return element;+ };+ elements.push({ name, declared: add("declared"), paused: add("paused") });+ });+ const style = document.createElement("style");+ style.textContent = css;+ document.head.append(style);++ const values = element => {+ const style = getComputedStyle(element);+ return `--p: ${style.getPropertyValue("--p")}, --q: ${style.getPropertyValue("--q")}`;+ };+ elements.forEach(({ paused }) => values(paused));+ await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));++ for (const { name, declared, paused } of elements) {+ println(`${name}: ${values(declared)}`);+ if (values(paused) !== values(declared))+ println(` paused differs: ${values(paused)}`);+ }+ done();+ });+</script>