Skip to content

Truly independent web browser

LibWeb+Meta: Implement CSSStyleDeclaration bindings in Rust

Andreas Kling6151b7a672d4
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_descriptors.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_descriptors.rs
index 14ada8baf1c..c60498bc5eb 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_descriptors.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_descriptors.rs
@@ -4,74 +4,8 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! What the interfaces that inherit from CSSStyleDeclaration, which LibWeb implements in C++, share: each owns a
-//! C++ declaration block and has an attribute for each of its properties or descriptors.
-
-use core::ffi::c_void;
-use core::ptr::NonNull;
-
-use ak::Utf16String;
-use libjs_rust::api::Trace;
-
-use crate::bindings::cpp_cell::CppCell;
-use crate::bindings::interface::{Interface, Ref, cell_into_abi};
-use crate::bindings::{Exception, WebIdlResult};
-
-unsafe extern "C" {
- fn web_css_descriptors_set_owner(descriptors: *mut c_void, interface_name: u16, owner: *mut c_void);
- fn web_css_descriptors_get(descriptors: *mut c_void, name: *const u8, name_length: usize) -> usize;
- fn web_css_descriptors_set(
- descriptors: *mut c_void,
- name: *const u8,
- name_length: usize,
- value: usize,
- error_message: *mut usize,
- ) -> bool;
-}
-
-/// The Web::CSS::RustCSSDescriptors that an object of a descriptors interface owns.
-#[derive(Trace)]
-#[gc(crate = libjs_rust)]
-pub(crate) struct CppDescriptors(CppCell);
-
-impl CppDescriptors {
- pub(crate) fn new(cell: CppCell) -> Self {
- Self(cell)
- }
-
- pub(crate) fn as_cpp_parent(&self) -> Option<NonNull<c_void>> {
- NonNull::new(self.0.as_ptr())
- }
-
- pub(crate) fn set_owner<T: Interface>(&self, owner: Ref<T>) {
- // SAFETY: The cells are live, and the owner keeps the descriptors alive.
- unsafe { web_css_descriptors_set_owner(self.0.as_ptr(), T::INTERFACE_NAME, cell_into_abi(owner)) };
- }
-
- pub(crate) fn get(&self, name: &str) -> Utf16String {
- // SAFETY: The cell is live, the name is lent for the call, and LibWeb hands over the string.
- unsafe { Utf16String::from_raw_owned(web_css_descriptors_get(self.0.as_ptr(), name.as_ptr(), name.len())) }
- }
-
- pub(crate) fn set(&self, name: &str, value: Utf16String) -> WebIdlResult<()> {
- let mut error_message = 0;
- // SAFETY: The cell is live, the name is lent for the call, and the value is handed over.
- if unsafe {
- web_css_descriptors_set(
- self.0.as_ptr(),
- name.as_ptr(),
- name.len(),
- value.into_raw(),
- &raw mut error_message,
- )
- } {
- return Ok(());
- }
- // SAFETY: LibWeb hands over the message of the exception.
- let message = unsafe { Utf16String::from_raw_owned(error_message) };
- Err(Exception::Dom("NoModificationAllowedError", message))
- }
-}
+//! What the interfaces of the descriptors of an at-rule share: each is a CSSStyleDeclaration with an attribute for each
+//! descriptor.
/// An interface of the descriptors of an at-rule, with the entry point through which LibWeb creates its objects, and
/// the getter and the setter of each descriptor.
@@ -80,12 +14,20 @@ macro_rules! descriptors_interface {
#[derive(libjs_rust::api::Trace)]
#[gc(crate = libjs_rust)]
pub(crate) struct $interface {
- descriptors: $crate::css::css_descriptors::CppDescriptors,
+ declaration: $crate::css::css_style_declaration::CSSStyleDeclaration,
}
impl $crate::bindings::interface::Wrappable for $interface {
fn cpp_parent(&self) -> Option<core::ptr::NonNull<core::ffi::c_void>> {
- self.descriptors.as_cpp_parent()
+ self.declaration.as_cpp_parent()
+ }
+ }
+
+ impl $crate::bindings::interface::Inherits<$crate::css::css_style_declaration::CSSStyleDeclaration>
+ for $interface
+ {
+ fn parent(&self) -> &$crate::css::css_style_declaration::CSSStyleDeclaration {
+ &self.declaration
}
}
@@ -95,7 +37,7 @@ macro_rules! descriptors_interface {
&self,
_: &mut $crate::bindings::CallContext,
) -> $crate::bindings::WebIdlResult<ak::Utf16String> {
- Ok(self.descriptors.get($name))
+ Ok(self.declaration.get($name))
}
pub(crate) fn $setter(
@@ -103,7 +45,7 @@ macro_rules! descriptors_interface {
_: &mut $crate::bindings::CallContext,
value: ak::Utf16String,
) -> $crate::bindings::WebIdlResult<()> {
- self.descriptors.set($name, value)
+ self.declaration.set($name, value)
}
)+
}
@@ -121,9 +63,9 @@ macro_rules! descriptors_interface {
(&*vm.cast::<libjs_rust::api::Vm>(), $crate::bindings::cpp_cell::CppCell::from_raw(descriptors))
};
let object = $crate::bindings::interface::allocate(vm, |_| $interface {
- descriptors: $crate::css::css_descriptors::CppDescriptors::new(descriptors),
+ declaration: $crate::css::css_style_declaration::CSSStyleDeclaration::new(descriptors),
});
- object.descriptors.set_owner(object);
+ object.declaration.set_owner(object);
}
};
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_font_face_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_font_face_rule.rs
index bf865630284..165dd1e84d0 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_font_face_rule.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_font_face_rule.rs
@@ -6,10 +6,10 @@
//! CSSFontFaceRule, https://drafts.csswg.org/css-fonts/#om-fontface
+use super::css_font_face_descriptors::CSSFontFaceDescriptors;
use super::css_rule::CSSRule;
use super::css_rule::RuleText;
use super::css_rule::impl_rule_wrappable;
-use crate::bindings::conversions::CppInterface;
use crate::bindings::interface::{Inherits, Ref, allocate};
use crate::bindings::{CallContext, WebIdlResult};
use ak::Utf16String;
@@ -46,8 +46,8 @@ impl CSSFontFaceRule {
}
// https://drafts.csswg.org/css-fonts/#dom-cssfontfacerule-style
- pub(crate) fn style(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
- Ok(self.rule.style_attribute(cx))
+ pub(crate) fn style(&self, cx: &mut CallContext) -> WebIdlResult<Ref<CSSFontFaceDescriptors>> {
+ Ok(self.rule.declarations_object(cx))
}
fn descriptor(&self, name: &str) -> Option<Utf16String> {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_function_declarations.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_function_declarations.rs
index 996edfb31b5..62281d28ce5 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_function_declarations.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_function_declarations.rs
@@ -6,9 +6,9 @@
//! CSSFunctionDeclarations, https://drafts.csswg.org/css-mixins-1/#cssfunctiondeclarations
+use super::css_function_descriptors::CSSFunctionDescriptors;
use super::css_rule::CSSRule;
use super::css_rule::impl_rule_wrappable;
-use crate::bindings::conversions::CppInterface;
use crate::bindings::interface::{Inherits, Ref, allocate};
use crate::bindings::{CallContext, WebIdlResult};
use ak::Utf16String;
@@ -42,8 +42,8 @@ impl CSSFunctionDeclarations {
}
// https://drafts.csswg.org/css-mixins-1/#dom-cssfunctiondeclarations-style
- pub(crate) fn style(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
- Ok(self.rule.style_attribute(cx))
+ pub(crate) fn style(&self, cx: &mut CallContext) -> WebIdlResult<Ref<CSSFunctionDescriptors>> {
+ Ok(self.rule.declarations_object(cx))
}
pub(crate) fn serialized(&self, vm: &Vm) -> Utf16String {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_page_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_page_rule.rs
index fed02bfd8ea..726131cdedb 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_page_rule.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_page_rule.rs
@@ -7,9 +7,9 @@
//! CSSPageRule, https://drafts.csswg.org/cssom/#the-csspagerule-interface
use super::css_grouping_rule::CSSGroupingRule;
+use super::css_page_descriptors::CSSPageDescriptors;
use super::css_rule::impl_rule_wrappable;
use super::css_rule::{CSSRule, RuleText, serialized_rules};
-use crate::bindings::conversions::CppInterface;
use crate::bindings::interface::{Inherits, Ref, allocate};
use crate::bindings::{CallContext, WebIdlResult};
use ak::Utf16String;
@@ -62,8 +62,8 @@ impl CSSPageRule {
}
// https://drafts.csswg.org/cssom/#dom-csspagerule-style
- pub(crate) fn style(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
- Ok(self.rule().style_attribute(cx))
+ pub(crate) fn style(&self, cx: &mut CallContext) -> WebIdlResult<Ref<CSSPageDescriptors>> {
+ Ok(self.rule().declarations_object(cx))
}
// https://drafts.csswg.org/cssom/#ref-for-csspagerule
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_rule.rs
index 30a4ec8b378..9553c822a1c 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_rule.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_rule.rs
@@ -183,11 +183,6 @@ impl CSSRule {
unsafe { cell_from_abi(web_css_declaration_owner(declarations.as_ptr())) }
}
- /// The object that the `style` attribute of the rule returns.
- pub(crate) fn style_attribute(&self, cx: &CallContext) -> CppInterface {
- wrap_cpp_cell(cx, &self.declarations(cx.vm()))
- }
-
// https://drafts.csswg.org/cssom/#dom-cssrule-csstext
pub(crate) fn css_text(&self, cx: &mut CallContext) -> WebIdlResult<Utf16String> {
// The cssText attribute must return a serialization of the CSS rule.
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_style_declaration.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_style_declaration.rs
new file mode 100644
index 00000000000..54c98fcada5
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_style_declaration.rs
@@ -0,0 +1,221 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSStyleDeclaration, https://drafts.csswg.org/cssom/#the-cssstyledeclaration-interface
+
+use core::ffi::c_void;
+use core::ptr::NonNull;
+
+use ak::Utf16String;
+use libjs_rust::api::Trace;
+
+use super::css_rule::AnyCSSRule;
+use super::exports::rule_from_abi;
+use crate::bindings::cpp_cell::CppCell;
+use crate::bindings::interface::{Interface, Ref, Wrappable, cell_into_abi};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+unsafe extern "C" {
+ fn web_css_declaration_set_owner(declaration: *mut c_void, interface_name: u16, owner: *mut c_void);
+ fn web_css_declaration_get_by_name(declaration: *mut c_void, name: *const u8, name_length: usize) -> usize;
+ fn web_css_declaration_set_by_name(
+ declaration: *mut c_void,
+ name: *const u8,
+ name_length: usize,
+ value: usize,
+ error_message: *mut usize,
+ ) -> bool;
+ fn web_css_declaration_css_text(declaration: *mut c_void) -> usize;
+ fn web_css_declaration_set_css_text(declaration: *mut c_void, text: usize, error_message: *mut usize) -> bool;
+ fn web_css_declaration_length(declaration: *mut c_void) -> usize;
+ fn web_css_declaration_item(declaration: *mut c_void, index: usize) -> usize;
+ fn web_css_declaration_get_property_value(declaration: *mut c_void, property: usize) -> usize;
+ fn web_css_declaration_get_property_priority(declaration: *mut c_void, property: usize) -> usize;
+ fn web_css_declaration_set_property(
+ declaration: *mut c_void,
+ property: usize,
+ value: usize,
+ priority: usize,
+ error_message: *mut usize,
+ ) -> bool;
+ fn web_css_declaration_remove_property(
+ declaration: *mut c_void,
+ property: usize,
+ removed_value: *mut usize,
+ error_message: *mut usize,
+ ) -> bool;
+ fn web_css_declaration_parent_rule(declaration: *mut c_void) -> *mut c_void;
+}
+
+/// What every interface that inherits from CSSStyleDeclaration has: the Web::CSS::CSSStyleDeclaration that holds the
+/// declarations.
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSStyleDeclaration {
+ declaration: CppCell,
+}
+
+impl Wrappable for CSSStyleDeclaration {}
+
+/// What a step that LibWeb runs says: `Ok` if it succeeded, and the message of the exception otherwise.
+fn result_of_step(succeeded: bool, error_message: usize) -> WebIdlResult<()> {
+ if succeeded {
+ return Ok(());
+ }
+ // SAFETY: LibWeb hands over the message of the exception.
+ let message = unsafe { Utf16String::from_raw_owned(error_message) };
+ Err(Exception::Dom("NoModificationAllowedError", message))
+}
+
+impl CSSStyleDeclaration {
+ pub(crate) fn new(declaration: CppCell) -> Self {
+ Self { declaration }
+ }
+
+ /// The C++ object that the wrappers of the object hold as their wrappable, which the wrapper caches of LibWeb's C++
+ /// bindings look for.
+ pub(crate) fn as_cpp_parent(&self) -> Option<NonNull<c_void>> {
+ NonNull::new(self.declaration.as_ptr())
+ }
+
+ pub(crate) fn set_owner<T: Interface>(&self, owner: Ref<T>) {
+ // SAFETY: The cells are live, and the owner keeps the declaration alive.
+ unsafe { web_css_declaration_set_owner(self.declaration.as_ptr(), T::INTERFACE_NAME, cell_into_abi(owner)) };
+ }
+
+ /// The value of the property or descriptor, whose name is one the bindings know.
+ pub(crate) fn get(&self, name: &str) -> Utf16String {
+ // SAFETY: The cell is live, the name is lent for the call, and LibWeb hands over the string.
+ unsafe {
+ Utf16String::from_raw_owned(web_css_declaration_get_by_name(
+ self.declaration.as_ptr(),
+ name.as_ptr(),
+ name.len(),
+ ))
+ }
+ }
+
+ /// Sets the property or descriptor, whose name is one the bindings know.
+ pub(crate) fn set(&self, name: &str, value: Utf16String) -> WebIdlResult<()> {
+ let mut error_message = 0;
+ // SAFETY: The cell is live, the name is lent for the call, and the value is handed over.
+ let succeeded = unsafe {
+ web_css_declaration_set_by_name(
+ self.declaration.as_ptr(),
+ name.as_ptr(),
+ name.len(),
+ value.into_raw(),
+ &raw mut error_message,
+ )
+ };
+ result_of_step(succeeded, error_message)
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssstyledeclaration-csstext
+ pub(crate) fn css_text(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ // SAFETY: The cell is live, and LibWeb hands over the string.
+ Ok(unsafe { Utf16String::from_raw_owned(web_css_declaration_css_text(self.declaration.as_ptr())) })
+ }
+
+ pub(crate) fn set_css_text(&self, _: &mut CallContext, value: Utf16String) -> WebIdlResult<()> {
+ let mut error_message = 0;
+ // SAFETY: The cell is live, and the value is handed over.
+ let succeeded = unsafe {
+ web_css_declaration_set_css_text(self.declaration.as_ptr(), value.into_raw(), &raw mut error_message)
+ };
+ result_of_step(succeeded, error_message)
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssstyledeclaration-length
+ pub(crate) fn length(&self, _: &mut CallContext) -> WebIdlResult<u32> {
+ // SAFETY: The cell is live.
+ let length = unsafe { web_css_declaration_length(self.declaration.as_ptr()) };
+ Ok(u32::try_from(length).expect("a declaration block has fewer than 2^32 declarations"))
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssstyledeclaration-item
+ pub(crate) fn item(&self, _: &mut CallContext, index: u32) -> WebIdlResult<Utf16String> {
+ // SAFETY: The cell is live, and LibWeb hands over the string.
+ Ok(unsafe { Utf16String::from_raw_owned(web_css_declaration_item(self.declaration.as_ptr(), index as usize)) })
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssstyledeclaration-getpropertyvalue
+ pub(crate) fn get_property_value(&self, _: &mut CallContext, property: Utf16String) -> WebIdlResult<Utf16String> {
+ // SAFETY: The cell is live, the name is handed over, and LibWeb hands over the string.
+ Ok(unsafe {
+ Utf16String::from_raw_owned(web_css_declaration_get_property_value(
+ self.declaration.as_ptr(),
+ property.into_raw(),
+ ))
+ })
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssstyledeclaration-getpropertypriority
+ pub(crate) fn get_property_priority(
+ &self,
+ _: &mut CallContext,
+ property: Utf16String,
+ ) -> WebIdlResult<Utf16String> {
+ // SAFETY: The cell is live, the name is handed over, and LibWeb hands over the string.
+ Ok(unsafe {
+ Utf16String::from_raw_owned(web_css_declaration_get_property_priority(
+ self.declaration.as_ptr(),
+ property.into_raw(),
+ ))
+ })
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssstyledeclaration-setproperty
+ pub(crate) fn set_property(
+ &self,
+ _: &mut CallContext,
+ property: Utf16String,
+ value: Utf16String,
+ priority: Utf16String,
+ ) -> WebIdlResult<()> {
+ let mut error_message = 0;
+ // SAFETY: The cell is live, and the strings are handed over.
+ let succeeded = unsafe {
+ web_css_declaration_set_property(
+ self.declaration.as_ptr(),
+ property.into_raw(),
+ value.into_raw(),
+ priority.into_raw(),
+ &raw mut error_message,
+ )
+ };
+ result_of_step(succeeded, error_message)
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssstyledeclaration-removeproperty
+ pub(crate) fn remove_property(&self, _: &mut CallContext, property: Utf16String) -> WebIdlResult<Utf16String> {
+ let mut removed_value = 0;
+ let mut error_message = 0;
+ // SAFETY: The cell is live, and the name is handed over.
+ let succeeded = unsafe {
+ web_css_declaration_remove_property(
+ self.declaration.as_ptr(),
+ property.into_raw(),
+ &raw mut removed_value,
+ &raw mut error_message,
+ )
+ };
+ result_of_step(succeeded, error_message)?;
+ // SAFETY: LibWeb hands over the value.
+ Ok(unsafe { Utf16String::from_raw_owned(removed_value) })
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssstyledeclaration-parentrule
+ pub(crate) fn parent_rule(&self, _: &mut CallContext) -> WebIdlResult<Option<AnyCSSRule>> {
+ // SAFETY: The cell is live.
+ let rule = unsafe { web_css_declaration_parent_rule(self.declaration.as_ptr()) };
+ if rule.is_null() {
+ return Ok(None);
+ }
+ // SAFETY: LibWeb returns the live cell of a rule.
+ Ok(Some(unsafe { rule_from_abi(rule) }))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_style_properties.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_style_properties.rs
index 16237330512..615a99f7494 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_style_properties.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_style_properties.rs
@@ -15,9 +15,9 @@ use libjs_rust::api::{
};
use libweb_rust::css_property_names;
-use super::css_descriptors::CppDescriptors;
+use super::css_style_declaration::CSSStyleDeclaration;
use crate::bindings::cpp_cell::CppCell;
-use crate::bindings::interface::{Wrappable, allocate};
+use crate::bindings::interface::{Inherits, Wrappable, allocate};
use crate::bindings::{CallContext, WebIdlResult};
/// What an accessor of a CSS property captures. NB: The name is static, so the collector has nothing to see in it.
@@ -31,7 +31,7 @@ pub(crate) struct CSSPropertyAccessor {
#[derive(Trace)]
#[gc(crate = libjs_rust)]
pub(crate) struct CSSStyleProperties {
- declaration: CppDescriptors,
+ declaration: CSSStyleDeclaration,
}
impl Wrappable for CSSStyleProperties {
@@ -40,6 +40,12 @@ impl Wrappable for CSSStyleProperties {
}
}
+impl Inherits<CSSStyleDeclaration> for CSSStyleProperties {
+ fn parent(&self) -> &CSSStyleDeclaration {
+ &self.declaration
+ }
+}
+
/// https://drafts.csswg.org/cssom/#css-property-to-idl-attribute
fn css_property_to_idl_attribute(property: &str, lowercase_first: bool) -> String {
// 1. Let output be the empty string.
@@ -150,7 +156,7 @@ pub unsafe extern "C" fn web_css_style_properties_create(vm: *mut c_void, declar
// SAFETY: The caller passes the live VM and a live cell.
let (vm, declaration) = unsafe { (&*vm.cast::<Vm>(), CppCell::from_raw(declaration)) };
let object = allocate(vm, |_| CSSStyleProperties {
- declaration: CppDescriptors::new(declaration),
+ declaration: CSSStyleDeclaration::new(declaration),
});
object.declaration.set_owner(object);
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs
index 91b2b3f9f32..a85a7efe220 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs
@@ -55,6 +55,7 @@ pub(crate) mod css_scope_rule;
pub(crate) mod css_skew;
pub(crate) mod css_skew_x;
pub(crate) mod css_skew_y;
+pub(crate) mod css_style_declaration;
pub(crate) mod css_style_properties;
pub(crate) mod css_style_rule;
pub(crate) mod css_style_sheet;
diff --git a/Libraries/LibWeb/CSS/CSSStyleDeclaration.cpp b/Libraries/LibWeb/CSS/CSSStyleDeclaration.cpp
index 758f59902a6..7ac35c6e2d1 100644
--- a/Libraries/LibWeb/CSS/CSSStyleDeclaration.cpp
+++ b/Libraries/LibWeb/CSS/CSSStyleDeclaration.cpp
@@ -124,12 +124,21 @@ void CSSStyleDeclaration::set_owner_node(Optional<DOM::AbstractElement> owner_no
m_owner_pseudo_element = owner_node->pseudo_element();
}
-// Declared on the Rust side in Libraries/LibWeb/Bindings/Rust/src/css/css_descriptors.rs.
+// Declared on the Rust side in Libraries/LibWeb/Bindings/Rust/src/css/css_style_declaration.rs and css_rule.rs.
extern "C" {
-void web_css_descriptors_set_owner(void* declaration, u16 interface_name, void* owner);
+void web_css_declaration_set_owner(void* declaration, u16 interface_name, void* owner);
void* web_css_declaration_owner(void* declaration);
-FlatPtr web_css_descriptors_get(void* declaration, u8 const* name, size_t name_length);
-bool web_css_descriptors_set(void* declaration, u8 const* name, size_t name_length, FlatPtr value, FlatPtr* error_message);
+FlatPtr web_css_declaration_get_by_name(void* declaration, u8 const* name, size_t name_length);
+bool web_css_declaration_set_by_name(void* declaration, u8 const* name, size_t name_length, FlatPtr value, FlatPtr* error_message);
+FlatPtr web_css_declaration_css_text(void* declaration);
+bool web_css_declaration_set_css_text(void* declaration, FlatPtr text, FlatPtr* error_message);
+size_t web_css_declaration_length(void* declaration);
+FlatPtr web_css_declaration_item(void* declaration, size_t index);
+FlatPtr web_css_declaration_get_property_value(void* declaration, FlatPtr property);
+FlatPtr web_css_declaration_get_property_priority(void* declaration, FlatPtr property);
+bool web_css_declaration_set_property(void* declaration, FlatPtr property, FlatPtr value, FlatPtr priority, FlatPtr* error_message);
+bool web_css_declaration_remove_property(void* declaration, FlatPtr property, FlatPtr* removed_value, FlatPtr* error_message);
+void* web_css_declaration_parent_rule(void* declaration);
}
static CSSStyleDeclaration& declaration_from_cell(void* cell)
@@ -137,12 +146,27 @@ static CSSStyleDeclaration& declaration_from_cell(void* cell)
return *static_cast<CSSStyleDeclaration*>(static_cast<GC::Cell*>(cell));
}
-static Utf16FlyString property_name(u8 const* name, size_t name_length)
+static Utf16FlyString property_name_from_utf8(u8 const* name, size_t name_length)
{
return Utf16FlyString::from_utf8_without_validation(StringView { name, name_length });
}
-void web_css_descriptors_set_owner(void* declaration, u16 interface_name, void* owner)
+static Utf16FlyString property_name_from_raw(FlatPtr property)
+{
+ return Utf16FlyString { Utf16String::from_raw(property) };
+}
+
+// NB: Every step that throws throws a NoModificationAllowedError, which the Rust bindings recreate from its message.
+template<typename T>
+static bool succeeded_or_store_message(WebIDL::ExceptionOr<T> const& result, FlatPtr* error_message)
+{
+ if (!result.is_error())
+ return true;
+ *error_message = result.exception().template get<GC::Ref<WebIDL::DOMException>>()->message().to_utf16_string().into_raw();
+ return false;
+}
+
+void web_css_declaration_set_owner(void* declaration, u16 interface_name, void* owner)
{
declaration_from_cell(declaration).set_owner(static_cast<Bindings::InterfaceName>(interface_name), *static_cast<Bindings::RustInterfaceCell*>(owner));
}
@@ -152,21 +176,67 @@ void* web_css_declaration_owner(void* declaration)
return &declaration_from_cell(declaration).ensure_owner();
}
-FlatPtr web_css_descriptors_get(void* declaration, u8 const* name, size_t name_length)
+FlatPtr web_css_declaration_get_by_name(void* declaration, u8 const* name, size_t name_length)
{
- return declaration_from_cell(declaration).get_property_value(property_name(name, name_length)).into_raw();
+ return declaration_from_cell(declaration).get_property_value(property_name_from_utf8(name, name_length)).into_raw();
}
-bool web_css_descriptors_set(void* declaration, u8 const* name, size_t name_length, FlatPtr value, FlatPtr* error_message)
+bool web_css_declaration_set_by_name(void* declaration, u8 const* name, size_t name_length, FlatPtr value, FlatPtr* error_message)
{
auto text = Utf16String::from_raw(value);
- auto result = declaration_from_cell(declaration).set_property(property_name(name, name_length), text.utf16_view(), u""sv);
- if (!result.is_error())
- return true;
- auto exception = result.release_error();
- auto message = exception.get<GC::Ref<WebIDL::DOMException>>()->message();
- *error_message = Utf16String(message).into_raw();
- return false;
+ return succeeded_or_store_message(declaration_from_cell(declaration).set_property(property_name_from_utf8(name, name_length), text.utf16_view(), u""sv), error_message);
+}
+
+FlatPtr web_css_declaration_css_text(void* declaration)
+{
+ return declaration_from_cell(declaration).css_text().into_raw();
+}
+
+bool web_css_declaration_set_css_text(void* declaration, FlatPtr text, FlatPtr* error_message)
+{
+ auto css_text = Utf16String::from_raw(text);
+ return succeeded_or_store_message(declaration_from_cell(declaration).set_css_text(css_text.utf16_view()), error_message);
+}
+
+size_t web_css_declaration_length(void* declaration)
+{
+ return declaration_from_cell(declaration).length();
+}
+
+FlatPtr web_css_declaration_item(void* declaration, size_t index)
+{
+ return declaration_from_cell(declaration).item(index).into_raw();
+}
+
+FlatPtr web_css_declaration_get_property_value(void* declaration, FlatPtr property)
+{
+ return declaration_from_cell(declaration).get_property_value(property_name_from_raw(property)).into_raw();
+}
+
+FlatPtr web_css_declaration_get_property_priority(void* declaration, FlatPtr property)
+{
+ return declaration_from_cell(declaration).get_property_priority(property_name_from_raw(property)).into_raw();
+}
+
+bool web_css_declaration_set_property(void* declaration, FlatPtr property, FlatPtr value, FlatPtr priority, FlatPtr* error_message)
+{
+ auto value_text = Utf16String::from_raw(value);
+ auto priority_text = Utf16String::from_raw(priority);
+ return succeeded_or_store_message(declaration_from_cell(declaration).set_property(property_name_from_raw(property), value_text.utf16_view(), priority_text.utf16_view()), error_message);
+}
+
+bool web_css_declaration_remove_property(void* declaration, FlatPtr property, FlatPtr* removed_value, FlatPtr* error_message)
+{
+ auto result = declaration_from_cell(declaration).remove_property(property_name_from_raw(property));
+ if (!succeeded_or_store_message(result, error_message))
+ return false;
+ *removed_value = result.release_value().into_raw();
+ return true;
+}
+
+void* web_css_declaration_parent_rule(void* declaration)
+{
+ return declaration_from_cell(declaration).parent_rule().ptr();
}
}
diff --git a/Libraries/LibWeb/CSS/CSSStyleDeclaration.h b/Libraries/LibWeb/CSS/CSSStyleDeclaration.h
index 19bbc1da6d7..6a9a87dce20 100644
--- a/Libraries/LibWeb/CSS/CSSStyleDeclaration.h
+++ b/Libraries/LibWeb/CSS/CSSStyleDeclaration.h
@@ -23,7 +23,7 @@ namespace Web::CSS {
// https://drafts.csswg.org/cssom/#css-declaration-blocks
class CSSStyleDeclaration
: public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(CSSStyleDeclaration, Bindings::GCAllocatedWrappable);
+ WEB_NON_IDL_WRAPPABLE(CSSStyleDeclaration, Bindings::GCAllocatedWrappable);
GC_DECLARE_ALLOCATOR(CSSStyleDeclaration);
public:
diff --git a/Libraries/LibWeb/CSS/CSSStyleDeclaration.idl b/Libraries/LibWeb/CSS/CSSStyleDeclaration.idl
index 95c87cbd7db..efd9c89a222 100644
--- a/Libraries/LibWeb/CSS/CSSStyleDeclaration.idl
+++ b/Libraries/LibWeb/CSS/CSSStyleDeclaration.idl
@@ -1,5 +1,5 @@
// https://drafts.csswg.org/cssom/#cssstyledeclaration
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSStyleDeclaration {
[CEReactions] attribute CSSOMString cssText;
diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.py
index af6fa3799d6..8800a59f76b 100644
--- a/Meta/Generators/libweb_bindings/rust_bindings.py
+++ b/Meta/Generators/libweb_bindings/rust_bindings.py
@@ -266,11 +266,13 @@ void {interface.namespace_class}::initialize(JS::Realm& realm, JS::Object& objec
initialize_prototype = rust_entry_point_name(interface, "initialize_prototype")
initialize_constructor = rust_entry_point_name(interface, "initialize_constructor")
construct = rust_entry_point_name(interface, "construct")
- supports_indexed_properties = rust_members(interface).indexed_property_getter is not None
+ # NB: An interface that inherits indexed properties reads them through the entry point of the interface defining them.
+ indexed_interface = rust_interface_with_indexed_properties(interface, context)
+ supports_indexed_properties = indexed_interface is not None
has_indexed_property_setter = rust_members(interface).indexed_property_setter is not None
- if supports_indexed_properties and inheriting_interfaces(interface, context):
+ if has_indexed_property_setter and inheriting_interfaces(interface, context):
raise UnsupportedByRustBindings(
- f"{interface.path}: {interface.name} supports indexed properties and others inherit from it, which the "
+ f"{interface.path}: {interface.name} has an indexed property setter and others inherit from it, which the "
"Rust bindings do not handle yet"
)
out.write(
@@ -283,7 +285,7 @@ void {initialize_constructor}(JSVM*, void* realm, JSObject* constructor);
)
if supports_indexed_properties:
out.write(
- f"bool {item_value_entry_point(interface)}(JSVM*, void* realm, JSObject* wrapper, size_t index, "
+ f"bool {item_value_entry_point(indexed_interface)}(JSVM*, void* realm, JSObject* wrapper, size_t index, "
"JSValue* out_value);\n"
)
if has_indexed_property_setter:
@@ -370,7 +372,7 @@ constexpr JSHostClass {wrapper_host_class_symbol(interface)} = JS::make_host_cla
static Optional<JS::Value> {wrapper_name(interface)}_item_value(JS::HostObject const& wrapper, WrapperWorld&, JS::Realm& realm, size_t index)
{{
JSValue value {{}};
- if (!{item_value_entry_point(interface)}(JS::HostABI::vm_to_abi(realm.vm()), &realm, JS::HostABI::object_to_abi(const_cast<JS::HostObject*>(&wrapper)), index, &value))
+ if (!{item_value_entry_point(indexed_interface)}(JS::HostABI::vm_to_abi(realm.vm()), &realm, JS::HostABI::object_to_abi(const_cast<JS::HostObject*>(&wrapper)), index, &value))
return {{}};
return JS::HostABI::value_from_abi(value);
}}
@@ -1497,6 +1499,17 @@ def cpp_ancestor_with_indexed_properties(interface: Interface, context: Generati
return None
+def rust_interface_with_indexed_properties(interface: Interface, context: GenerationContext) -> Optional[Interface]:
+ """The interface implemented in Rust that defines the indexed properties of the interface: itself or the closest
+ ancestor implemented in Rust that has them, if any."""
+ candidate: Optional[Interface] = interface
+ while candidate is not None and is_implemented_in_rust(candidate):
+ if rust_members(candidate).indexed_property_getter is not None:
+ return candidate
+ candidate = context.interfaces.get(candidate.parent_name)
+ return None
+
+
def item_value_entry_point(interface: Interface) -> str:
return rust_entry_point_name(interface, "item_value")
@@ -1509,6 +1522,9 @@ def write_rust_item_value(
https://webidl.spec.whatwg.org/#legacy-platform-object-getownproperty"""
getter = indexed_property_getter.operation
return_type = getter.operation.return_type
+ implementation = "implementation_of::<Implementation>(wrapper)"
+ if inheriting_interfaces(interface, context):
+ implementation = "receiver_of(wrapper)"
what = f"the indexed property getter of {interface.name}"
conversion = rust_to_js_value(return_type.without_nullable(), "value", "&cx", context, what)
if return_type.nullable:
@@ -1547,7 +1563,7 @@ def write_rust_item_value(
let Ok(index) = u32::try_from(index) else {{
return false;
}};
- let implementation = implementation_of::<Implementation>(wrapper);
+ let implementation = {implementation};
let mut cx = CallContext::new(vm, realm);
{value_steps}
let value = {conversion}.expect("converting an object to a JS value does not throw");
@@ -1801,7 +1817,7 @@ def write_this_implementation(out: TextIO, context: GenerationContext, interface
}}
"""
choices = f""" if let Some(object) = implementation_if::<Implementation>(object) {{
- return Ok((Receiver::{interface.name}(object), cx));
+ return Receiver::{interface.name}(object);
}}
"""
for other in inheriting:
@@ -1824,7 +1840,7 @@ def write_this_implementation(out: TextIO, context: GenerationContext, interface
{steps} }}
"""
choices += f""" if let Some(object) = implementation_if::<{path}>(object) {{
- return Ok((Receiver::{other.name}(object), cx));
+ return Receiver::{other.name}(object);
}}
"""
out.write(
@@ -1843,11 +1859,15 @@ def write_this_implementation(out: TextIO, context: GenerationContext, interface
}}
}}
+ /// The object that a wrapper of the interface wraps.
+ fn receiver_of(object: Gc<Object>) -> Receiver {{
+{choices} unreachable!("a wrapper of the interface wraps an object of it or of an interface that inherits from it")
+ }}
+
/// The object that an attribute or an operation runs on, and the context it runs in.
fn this_implementation(vm: &Vm) -> ThrowCompletionOr<(Receiver, CallContext<'_>)> {{
let (object, realm) = this_object(vm, Implementation::wrapper_class(), Implementation::NAME)?;
- let cx = CallContext::new(vm, realm);
-{choices} unreachable!("a wrapper of the interface wraps an object of it or of an interface that inherits from it")
+ Ok((receiver_of(object), CallContext::new(vm, realm)))
}}
"""
)
diff --git a/Meta/Generators/libweb_bindings/rust_types.py b/Meta/Generators/libweb_bindings/rust_types.py
index 564d7ca186a..68d6d913311 100644
--- a/Meta/Generators/libweb_bindings/rust_types.py
+++ b/Meta/Generators/libweb_bindings/rust_types.py
@@ -127,7 +127,7 @@ def is_implemented_in_rust(interface: Optional[Interface]) -> bool:
# The interfaces implemented in C++ that an interface implemented in Rust can inherit from
# (Libraries/LibWeb/Bindings/RustEventTarget.h).
-CPP_PARENT_INTERFACES = ("CSSStyleDeclaration", "EventTarget", "Event")
+CPP_PARENT_INTERFACES = ("EventTarget", "Event")
def cpp_ancestor(interface: Interface, context: GenerationContext) -> Optional[Interface]:
diff --git a/Tests/LibWeb/Text/expected/css/CSSStyleDeclaration-subclasses.txt b/Tests/LibWeb/Text/expected/css/CSSStyleDeclaration-subclasses.txt
new file mode 100644
index 00000000000..ad4503b1f81
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/CSSStyleDeclaration-subclasses.txt
@@ -0,0 +1,38 @@
+inline: CSSStyleProperties, instanceof CSSStyleDeclaration: true
+ length 1, items [color], item(0) color, past the end: "", undefined
+ own keys [0], 0 in style: true, 99 in style: false
+ cssText: color: green;
+CSSStyleRule: CSSStyleProperties, instanceof CSSStyleDeclaration: true
+ length 2, items [color,margin-top], item(0) color, past the end: "", undefined
+ own keys [0,1], 0 in style: true, 99 in style: false
+ cssText: color: red; margin-top: 1px !important;
+CSSFontFaceRule: CSSFontFaceDescriptors, instanceof CSSStyleDeclaration: true
+ length 2, items [font-family,src], item(0) font-family, past the end: "", undefined
+ own keys [0,1], 0 in style: true, 99 in style: false
+ cssText: font-family: "x"; src: url("x.woff");
+CSSPageRule: CSSPageDescriptors, instanceof CSSStyleDeclaration: true
+ length 1, items [margin-top], item(0) margin-top, past the end: "", undefined
+ own keys [0], 0 in style: true, 99 in style: false
+ cssText: margin-top: 1px;
+CSSPositionTryRule: CSSPositionTryDescriptors, instanceof CSSStyleDeclaration: true
+ length 2, items [top,left], item(0) top, past the end: "", undefined
+ own keys [0,1], 0 in style: true, 99 in style: false
+ cssText: top: 1px; left: 2px;
+CSSStyleRule: parentRule is the rule: true, same object: true
+CSSFontFaceRule: parentRule is the rule: true, same object: true
+CSSPageRule: parentRule is the rule: true, same object: true
+CSSPositionTryRule: parentRule is the rule: true, same object: true
+inline parentRule: null
+priority: "important", ""
+after setProperty: color: blue !important; margin-top: 1px !important;
+removeProperty: blue, margin-top: 1px !important;
+custom: 1
+cssText setter: width: 1px;, 1
+PutForwards: height: 2px;
+computed: CSSStyleProperties, length > 0: true, [0] is item(0): true, cssText: ""
+computed setProperty: NoModificationAllowedError: Cannot modify properties in result of getComputedStyle()
+computed removeProperty: NoModificationAllowedError: Cannot remove property: CSSStyleProperties is read-only.
+computed cssText: NoModificationAllowedError: Cannot modify properties: CSSStyleProperties is read-only.
+wrong this: TypeError: Not an object of type CSSStyleDeclaration
+constructor: TypeError: CSSStyleDeclaration is not a constructor
+subclass method on base: TypeError: Not an object of type CSSStyleProperties
diff --git a/Tests/LibWeb/Text/input/css/CSSStyleDeclaration-subclasses.html b/Tests/LibWeb/Text/input/css/CSSStyleDeclaration-subclasses.html
new file mode 100644
index 00000000000..a9568729eaf
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/CSSStyleDeclaration-subclasses.html
@@ -0,0 +1,61 @@
+<!DOCTYPE html>
+<style id="sheet">
+ .a { color: red; margin-top: 1px !important; }
+ @font-face { font-family: "x"; src: url(x.woff); }
+ @page { margin-top: 1px; }
+ @position-try --p { top: 1px; left: 2px; }
+</style>
+<div id="target" style="color: green"></div>
+<script src="../include.js"></script>
+<script>
+ test(() => {
+ const rules = [...document.getElementById("sheet").sheet.cssRules];
+ const declarations = [
+ ["inline", target.style],
+ ...rules.map(rule => [rule.constructor.name, rule.style]),
+ ];
+ for (const [name, style] of declarations) {
+ const items = [];
+ for (let i = 0; i < style.length; ++i)
+ items.push(style[i]);
+ println(`${name}: ${style.constructor.name}, instanceof CSSStyleDeclaration: ${style instanceof CSSStyleDeclaration}`);
+ println(` length ${style.length}, items [${items}], item(0) ${style.item(0)}, past the end: "${style.item(99)}", ${style[99]}`);
+ println(` own keys [${Object.keys(style)}], 0 in style: ${0 in style}, 99 in style: ${99 in style}`);
+ println(` cssText: ${style.cssText}`);
+ }
+
+ for (const rule of rules)
+ println(`${rule.constructor.name}: parentRule is the rule: ${rule.style.parentRule === rule}, same object: ${rule.style === rule.style}`);
+ println(`inline parentRule: ${target.style.parentRule}`);
+
+ const style = rules[0].style;
+ println(`priority: "${style.getPropertyPriority("margin-top")}", "${style.getPropertyPriority("color")}"`);
+ style.setProperty("color", "blue", "important");
+ println(`after setProperty: ${style.cssText}`);
+ println(`removeProperty: ${style.removeProperty("color")}, ${style.cssText}`);
+ style.setProperty("--custom", "1");
+ println(`custom: ${style.getPropertyValue("--custom")}`);
+ style.setProperty("margin-left", null);
+ style.cssText = "width: 1px";
+ println(`cssText setter: ${style.cssText}, ${style.length}`);
+ rules[0].style = "height: 2px";
+ println(`PutForwards: ${style.cssText}`);
+
+ const computed = getComputedStyle(target);
+ println(`computed: ${computed.constructor.name}, length > 0: ${computed.length > 0}, [0] is item(0): ${computed[0] === computed.item(0)}, cssText: "${computed.cssText}"`);
+ const attempt = (name, steps) => {
+ try {
+ steps();
+ println(`${name}: no exception`);
+ } catch (error) {
+ println(`${name}: ${error.name}: ${error.message}`);
+ }
+ };
+ attempt("computed setProperty", () => computed.setProperty("color", "red"));
+ attempt("computed removeProperty", () => computed.removeProperty("color"));
+ attempt("computed cssText", () => { computed.cssText = "color: red"; });
+ attempt("wrong this", () => CSSStyleDeclaration.prototype.item.call({}, 0));
+ attempt("constructor", () => new CSSStyleDeclaration());
+ attempt("subclass method on base", () => Object.getOwnPropertyDescriptor(CSSStyleProperties.prototype, "cssFloat").get.call(rules[1].style));
+ });
+</script>