Skip to content

Truly independent web browser

LibWeb: Implement MediaList in Rust

Andreas Kling12f391850351
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs
new file mode 100644
index 00000000000..771482b465a
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! What the C++ code of LibWeb asks of the interfaces of CSS, declared in Libraries/LibWeb/CSS/MediaList.cpp.
+
+use core::ffi::c_void;
+
+use libjs_rust::api::Vm;
+use libweb_rust::NativeMediaList;
+
+use super::media_list::MediaList;
+use crate::bindings::cpp_cell::CppCell;
+use crate::bindings::interface::{Ref, allocate, cell_from_abi, cell_into_abi};
+
+/// # Safety
+///
+/// `vm` must be the live VM.
+unsafe fn vm_from_abi<'vm>(vm: *mut c_void) -> &'vm Vm {
+ assert!(!vm.is_null(), "C++ passes the VM");
+ // SAFETY: The caller passes the live VM.
+ unsafe { &*vm.cast::<Vm>() }
+}
+
+/// The implementation of the MediaList whose cell C++ lends, for as long as C++ keeps the cell alive.
+///
+/// # Safety
+///
+/// `list` must be the live cell of a MediaList, and it must outlive `'a`.
+unsafe fn media_list_from_abi<'a>(list: *mut c_void) -> &'a MediaList {
+ // SAFETY: The caller passes a live cell of a MediaList.
+ let list: Ref<MediaList> = unsafe { cell_from_abi(list) };
+ // SAFETY: The caller keeps the cell alive for 'a.
+ unsafe { &*list.as_ptr() }
+}
+
+/// A new MediaList that shares the media queries of `media`.
+///
+/// # Safety
+///
+/// `vm` must be the live VM.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_media_list_create(vm: *mut c_void, media: &NativeMediaList) -> *mut c_void {
+ // SAFETY: The caller passes the live VM.
+ let vm = unsafe { vm_from_abi(vm) };
+ cell_into_abi(allocate(vm, |defer_gc| MediaList::new(defer_gc, media.clone())))
+}
+
+/// # Safety
+///
+/// `vm` must be the live VM, `list` the live cell of a MediaList, and `sheet` that of a CSSStyleSheet.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_media_list_set_associated_style_sheet(
+ vm: *mut c_void,
+ list: *mut c_void,
+ sheet: *mut c_void,
+) {
+ // SAFETY: The caller passes the live VM, and live cells of a MediaList and a CSSStyleSheet.
+ let (vm, list, sheet) = unsafe { (vm_from_abi(vm), media_list_from_abi(list), CppCell::from_raw(sheet)) };
+ list.set_associated_style_sheet(vm, sheet);
+}
+
+/// # Safety
+///
+/// `vm` must be the live VM, `list` the live cell of a MediaList, and `rule` that of a CSSRule.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_media_list_set_associated_rule(vm: *mut c_void, list: *mut c_void, rule: *mut c_void) {
+ // SAFETY: The caller passes the live VM, and live cells of a MediaList and a CSSRule.
+ let (vm, list, rule) = unsafe { (vm_from_abi(vm), media_list_from_abi(list), CppCell::from_raw(rule)) };
+ list.set_associated_rule(vm, rule);
+}
+
+/// A native list of its own with the media queries of the MediaList as they are now, which the caller frees.
+///
+/// # Safety
+///
+/// `list` must be the live cell of a MediaList.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_media_list_share_native_list(list: *mut c_void) -> *mut NativeMediaList {
+ // SAFETY: The caller passes a live cell of a MediaList, and keeps it alive for the call.
+ let media = unsafe { media_list_from_abi(list) }.share_media();
+ Box::into_raw(Box::new(media))
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/media_list.rs b/Libraries/LibWeb/Bindings/Rust/src/css/media_list.rs
new file mode 100644
index 00000000000..60f37286f2b
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/media_list.rs
@@ -0,0 +1,120 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! MediaList, https://drafts.csswg.org/cssom/#the-medialist-interface
+
+use core::ffi::c_void;
+use core::ptr::null_mut;
+
+use ak::Utf16String;
+use libjs_rust::api::{DeferGc, GcRefCell, Trace, Vm};
+use libweb_rust::{MediaListDeleteResult, NativeMediaList};
+
+use crate::bindings::cpp_cell::CppCell;
+use crate::bindings::interface::Wrappable;
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+unsafe extern "C" {
+ fn web_css_media_list_changed(style_sheet: *mut c_void, rule: *mut c_void);
+}
+
+/// A media list belongs to a sheet, to an `@media` or `@import` rule inside one, or to both, when the sheet of an
+/// `@import` rule arrives after its list was asked for. Both are gates on whether rules apply, so both have to say when
+/// the gate moves.
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct MediaList {
+ /// The collection of media queries, which the sheet or the rule reads as well.
+ #[gc(untraced)]
+ media: NativeMediaList,
+ /// The cell of the CSSStyleSheet.
+ associated_style_sheet: GcRefCell<Option<CppCell>>,
+ /// The cell of the CSSRule.
+ associated_rule: GcRefCell<Option<CppCell>>,
+}
+
+impl Wrappable for MediaList {}
+
+fn cell_pointer(cell: &GcRefCell<Option<CppCell>>) -> *mut c_void {
+ cell.borrow().as_ref().map_or(null_mut(), CppCell::as_ptr)
+}
+
+impl MediaList {
+ pub(crate) fn new(_: &DeferGc<'_>, media: NativeMediaList) -> Self {
+ Self {
+ media,
+ associated_style_sheet: GcRefCell::new(None),
+ associated_rule: GcRefCell::new(None),
+ }
+ }
+
+ pub(crate) fn share_media(&self) -> NativeMediaList {
+ self.media.share()
+ }
+
+ pub(crate) fn set_associated_style_sheet(&self, vm: &Vm, sheet: CppCell) {
+ *self.associated_style_sheet.borrow_mut(vm) = Some(sheet);
+ }
+
+ pub(crate) fn set_associated_rule(&self, vm: &Vm, rule: CppCell) {
+ *self.associated_rule.borrow_mut(vm) = Some(rule);
+ }
+
+ fn media_changed(&self) {
+ let style_sheet = cell_pointer(&self.associated_style_sheet);
+ let rule = cell_pointer(&self.associated_rule);
+ // SAFETY: The cells are a CSSStyleSheet and a CSSRule, or null, and the list keeps them alive.
+ unsafe { web_css_media_list_changed(style_sheet, rule) };
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-medialist-mediatext
+ pub(crate) fn media_text(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(Utf16String::from_utf16(&self.media.media_text()))
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-medialist-mediatext
+ pub(crate) fn set_media_text(&self, _: &mut CallContext, value: Utf16String) -> WebIdlResult<()> {
+ self.media.set_media_text(value.as_units());
+ self.media_changed();
+ Ok(())
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-medialist-length
+ pub(crate) fn length(&self, _: &mut CallContext) -> WebIdlResult<u32> {
+ Ok(u32::try_from(self.media.length()).expect("a list has fewer than 2^32 media queries"))
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-medialist-item
+ pub(crate) fn item(&self, _: &mut CallContext, index: u32) -> WebIdlResult<Option<Utf16String>> {
+ Ok(self
+ .media
+ .item(index as usize)
+ .map(|text| Utf16String::from_utf16(&text)))
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-medialist-appendmedium
+ pub(crate) fn append_medium(&self, _: &mut CallContext, medium: Utf16String) -> WebIdlResult<()> {
+ if self.media.append_medium(medium.as_units()) {
+ self.media_changed();
+ }
+ Ok(())
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-medialist-deletemedium
+ pub(crate) fn delete_medium(&self, _: &mut CallContext, medium: Utf16String) -> WebIdlResult<()> {
+ match self.media.delete_medium(medium.as_units()) {
+ MediaListDeleteResult::Invalid => Ok(()),
+ MediaListDeleteResult::NotFound => Err(Exception::Dom(
+ "NotFoundError",
+ Utf16String::from_utf8("Media query not found in list"),
+ )),
+ MediaListDeleteResult::Removed => {
+ self.media_changed();
+ Ok(())
+ }
+ }
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs
new file mode 100644
index 00000000000..28367d97f57
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs
@@ -0,0 +1,10 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The CSS Object Model, https://drafts.csswg.org/cssom/
+
+pub(crate) mod exports;
+pub(crate) mod media_list;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
index 57b4ea3aaf9..f52d303379e 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
@@ -55,6 +55,16 @@ pub(crate) mod canvas_2d;
pub(crate) mod compression;
#[cfg(not(test))]
pub(crate) mod crypto;
+#[cfg(not(test))]
+#[cfg_attr(
+ not(web_idl_bindings),
+ allow(dead_code, reason = "only the generated bindings use the interfaces")
+)]
+#[allow(
+ clippy::unnecessary_wraps,
+ reason = "the bindings call every attribute and operation as one that can throw"
+)]
+pub(crate) mod css;
#[cfg_attr(
not(web_idl_bindings),
allow(dead_code, reason = "only the generated bindings use the dictionaries")
diff --git a/Libraries/LibWeb/CSS/CSSMediaRule.cpp b/Libraries/LibWeb/CSS/CSSMediaRule.cpp
index d605d4df30f..f9a16f60c56 100644
--- a/Libraries/LibWeb/CSS/CSSMediaRule.cpp
+++ b/Libraries/LibWeb/CSS/CSSMediaRule.cpp
@@ -24,13 +24,13 @@ CSSMediaRule::CSSMediaRule(RustRule rule, CSSRuleList& rules)
{
}
-MediaList* CSSMediaRule::media() const
+GC::Ref<MediaList> CSSMediaRule::media() const
{
if (!m_media) {
- m_media = MediaList::create(m_media_list.retain());
+ m_media = MediaList::create(m_media_list);
m_media->set_associated_rule(const_cast<CSSMediaRule&>(*this));
}
- return m_media.ptr();
+ return *m_media;
}
void CSSMediaRule::visit_edges(GC::Cell::Visitor& visitor)
diff --git a/Libraries/LibWeb/CSS/CSSMediaRule.h b/Libraries/LibWeb/CSS/CSSMediaRule.h
index db7d09e1569..f347ae6adb3 100644
--- a/Libraries/LibWeb/CSS/CSSMediaRule.h
+++ b/Libraries/LibWeb/CSS/CSSMediaRule.h
@@ -26,7 +26,7 @@ public:
virtual Utf16String serialized_condition_text() const override;
bool matches() const { return m_media_list.matches(); }
- MediaList* media() const;
+ GC::Ref<MediaList> media() const;
RustMediaList const& native_media_list() const { return m_media_list; }
private:
diff --git a/Libraries/LibWeb/CSS/MediaList.cpp b/Libraries/LibWeb/CSS/MediaList.cpp
index fe7bd96bff6..7810b9a53c1 100644
--- a/Libraries/LibWeb/CSS/MediaList.cpp
+++ b/Libraries/LibWeb/CSS/MediaList.cpp
@@ -5,7 +5,9 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <LibGC/Heap.h>
+#include <LibJS/HostClassBuilder.h>
+#include <LibJS/Runtime/VM.h>
+#include <LibWeb/CSS/CSSRule.h>
#include <LibWeb/CSS/CSSStyleSheet.h>
#include <LibWeb/CSS/MediaList.h>
#include <LibWeb/CSS/StyleComputeFFI.h>
@@ -15,61 +17,56 @@
#include <LibWeb/DOM/Document.h>
#include <LibWeb/Dump.h>
#include <LibWeb/HTML/Window.h>
-#include <LibWeb/WebIDL/DOMException.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
namespace Web::CSS {
-GC_DEFINE_ALLOCATOR(MediaList);
+extern "C" {
-GC::Ref<MediaList> MediaList::create(RustMediaList media)
-{
- return GC::Heap::the().allocate<MediaList>(move(media));
-}
+// Defined in Bindings/Rust/src/css/exports.rs.
+void* web_media_list_create(JSVM*, Parser::ValueParserFFI::MediaList const*);
+void web_media_list_set_associated_style_sheet(JSVM*, void* list, void* sheet);
+void web_media_list_set_associated_rule(JSVM*, void* list, void* rule);
+Parser::ValueParserFFI::MediaList* web_media_list_share_native_list(void* list);
-MediaList::MediaList(RustMediaList media)
- : m_media(move(media))
-{
+// Declared in Bindings/Rust/src/css/media_list.rs.
+void web_css_media_list_changed(void* style_sheet, void* rule);
}
-void MediaList::visit_edges(GC::Cell::Visitor& visitor)
+GC::Ref<MediaList> MediaList::create(RustMediaList const& media)
{
- Base::visit_edges(visitor);
- visitor.visit(m_associated_style_sheet);
- visitor.visit(m_associated_cssom_sheet);
- visitor.visit(m_associated_rule);
+ return GC::Ref { *static_cast<MediaList*>(web_media_list_create(JS::HostABI::vm_to_abi(JS::VM::the()), media.handle())) };
}
-// https://www.w3.org/TR/cssom-1/#dom-medialist-mediatext
-Utf16String MediaList::media_text() const
+RustMediaList MediaList::share_native_list() const
{
- return m_media.media_text();
+ return RustMediaList { web_media_list_share_native_list(const_cast<MediaList*>(this)) };
}
-MediaList::~MediaList() = default;
-
void MediaList::set_associated_style_sheet(NonnullRefPtr<StyleSheetState> sheet)
{
- m_associated_cssom_sheet = &sheet->cssom_sheet();
- m_associated_style_sheet = move(sheet);
+ web_media_list_set_associated_style_sheet(JS::HostABI::vm_to_abi(JS::VM::the()), this, static_cast<GC::Cell*>(&sheet->cssom_sheet()));
}
-// Both owners reach the same place: the sheet whose rules the gate belongs to.
-RefPtr<StyleSheetState> MediaList::owning_style_sheet()
+void MediaList::set_associated_rule(GC::Ref<CSSRule> rule)
{
- if (m_associated_style_sheet)
- return m_associated_style_sheet;
- if (m_associated_rule)
- return m_associated_rule->parent_style_sheet();
- return {};
+ web_media_list_set_associated_rule(JS::HostABI::vm_to_abi(JS::VM::the()), this, static_cast<GC::Cell*>(rule.ptr()));
}
-void MediaList::invalidate_owners_for_media_change()
+void web_css_media_list_changed(void* style_sheet_cell, void* rule_cell)
{
- auto sheet = owning_style_sheet();
+ auto* style_sheet = static_cast<CSSStyleSheet*>(static_cast<GC::Cell*>(style_sheet_cell));
+ auto* rule = static_cast<CSSRule*>(static_cast<GC::Cell*>(rule_cell));
+
+ // Both owners reach the same place: the sheet whose rules the gate belongs to.
+ RefPtr<StyleSheetState> sheet;
+ if (style_sheet)
+ sheet = style_sheet->state();
+ else if (rule)
+ sheet = rule->parent_style_sheet();
if (!sheet)
return;
- if (m_associated_rule)
+
+ if (rule)
stop_sharing_compiled_style_sheet(*sheet);
invalidate_style_sheet_for_media_change(*sheet);
}
@@ -87,39 +84,6 @@ void invalidate_style_sheet_for_media_change(StyleSheetState& sheet)
record_stylesheet_rule_conditions(sheet);
}
-void MediaList::set_media_text(Utf16View text)
-{
- m_media.set_text(text);
- invalidate_owners_for_media_change();
-}
-
-// https://www.w3.org/TR/cssom-1/#dom-medialist-item
-Optional<Utf16String> MediaList::item(u32 index) const
-{
- return m_media.item(index);
-}
-
-// https://www.w3.org/TR/cssom-1/#dom-medialist-appendmedium
-void MediaList::append_medium(Utf16View medium)
-{
- if (m_media.append(medium))
- invalidate_owners_for_media_change();
-}
-
-// https://www.w3.org/TR/cssom-1/#dom-medialist-deletemedium
-WebIDL::ExceptionOr<void> MediaList::delete_medium(Utf16View medium)
-{
- auto result = m_media.remove(medium);
- if (result == Parser::ValueParserFFI::MediaListDeleteResult::Invalid)
- return {};
- if (result == Parser::ValueParserFFI::MediaListDeleteResult::NotFound)
- return WebIDL::NotFoundError::create("Media query not found in list"_utf16);
-
- invalidate_owners_for_media_change();
-
- return {};
-}
-
MediaEnvironmentSnapshot::MediaEnvironmentSnapshot(DOM::Document const& document)
{
if (!document.window())
diff --git a/Libraries/LibWeb/CSS/MediaList.h b/Libraries/LibWeb/CSS/MediaList.h
index 47c517ea105..a9bda762b7d 100644
--- a/Libraries/LibWeb/CSS/MediaList.h
+++ b/Libraries/LibWeb/CSS/MediaList.h
@@ -8,51 +8,26 @@
#pragma once
-#include <AK/Optional.h>
-#include <AK/String.h>
-#include <LibWeb/Bindings/Wrappable.h>
+#include <LibGC/Ptr.h>
+#include <LibWeb/Bindings/MediaList.h>
+#include <LibWeb/Bindings/RustInterface.h>
#include <LibWeb/CSS/RustMediaList.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
+#include <LibWeb/Forward.h>
namespace Web::CSS {
// https://www.w3.org/TR/cssom-1/#the-medialist-interface
-class MediaList final : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(MediaList, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(MediaList);
+class MediaList final : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(MediaList, media_list)
public:
- [[nodiscard]] static GC::Ref<MediaList> create(RustMediaList);
- virtual ~MediaList() override;
+ // The new list shares the media queries of the list it is created with.
+ [[nodiscard]] static GC::Ref<MediaList> create(RustMediaList const&);
- Utf16String media_text() const;
- void set_media_text(Utf16View);
- size_t length() const { return m_media.length(); }
- Optional<Utf16String> item(u32 index) const;
- void append_medium(Utf16View);
- WebIDL::ExceptionOr<void> delete_medium(Utf16View);
-
- RustMediaList const& native_list() const { return m_media; }
+ RustMediaList share_native_list() const;
void set_associated_style_sheet(NonnullRefPtr<StyleSheetState>);
-
- // A media list belongs either to a sheet or to an `@media` rule inside one. Both are gates on
- // whether rules apply, so both have to say when the gate moves - a rule's list said nothing at
- // all, and changing a group's media therefore changed no style.
- void set_associated_rule(GC::Ref<CSSRule> rule) { m_associated_rule = rule; }
-
-private:
- MediaList(RustMediaList);
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- RefPtr<StyleSheetState> owning_style_sheet();
- void invalidate_owners_for_media_change();
-
- RefPtr<StyleSheetState> m_associated_style_sheet;
- GC::Ptr<CSSStyleSheet> m_associated_cssom_sheet;
- GC::Ptr<CSSRule> m_associated_rule;
- RustMediaList m_media;
+ void set_associated_rule(GC::Ref<CSSRule>);
};
void invalidate_style_sheet_for_media_change(StyleSheetState&);
diff --git a/Libraries/LibWeb/CSS/MediaList.idl b/Libraries/LibWeb/CSS/MediaList.idl
index cef64f1c9ec..e3207878d7c 100644
--- a/Libraries/LibWeb/CSS/MediaList.idl
+++ b/Libraries/LibWeb/CSS/MediaList.idl
@@ -1,7 +1,7 @@
// https://drafts.csswg.org/cssom-1/#the-medialist-interface
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface MediaList {
- [LegacyNullToEmptyString] stringifier attribute CSSOMString mediaText;
+ stringifier attribute [LegacyNullToEmptyString] CSSOMString mediaText;
readonly attribute unsigned long length;
getter CSSOMString? item(unsigned long index);
undefined appendMedium(CSSOMString medium);
diff --git a/Libraries/LibWeb/CSS/RustMediaList.h b/Libraries/LibWeb/CSS/RustMediaList.h
index 972612a7370..6eb98a73173 100644
--- a/Libraries/LibWeb/CSS/RustMediaList.h
+++ b/Libraries/LibWeb/CSS/RustMediaList.h
@@ -90,8 +90,6 @@ public:
return Parser::ValueParserFFI::rust_media_list_evaluate(m_list, environment.ffi_environment());
}
void set_text(Utf16View text) const { Parser::ValueParserFFI::rust_media_list_set_text(m_list, view(text)); }
- bool append(Utf16View text) const { return Parser::ValueParserFFI::rust_media_list_append(m_list, view(text)); }
- Parser::ValueParserFFI::MediaListDeleteResult remove(Utf16View text) const { return Parser::ValueParserFFI::rust_media_list_delete(m_list, view(text)); }
Utf16String media_text() const
{
Utf16String result;
diff --git a/Libraries/LibWeb/CSS/StyleSheetImport.cpp b/Libraries/LibWeb/CSS/StyleSheetImport.cpp
index fb7b2cf5d33..6bb6edfe54e 100644
--- a/Libraries/LibWeb/CSS/StyleSheetImport.cpp
+++ b/Libraries/LibWeb/CSS/StyleSheetImport.cpp
@@ -274,7 +274,7 @@ GC::Ref<MediaList> StyleSheetImport::media() const
// AD-HOC: Return our own MediaList.
// https://github.com/w3c/csswg-drafts/issues/12063
if (!m_media) {
- m_media = MediaList::create(m_media_list.retain());
+ m_media = MediaList::create(m_media_list);
if (m_style_sheet)
m_media->set_associated_style_sheet(*m_style_sheet);
else
diff --git a/Libraries/LibWeb/CSS/StyleSheetState.cpp b/Libraries/LibWeb/CSS/StyleSheetState.cpp
index 102cbc50a20..a4d9a9a40c0 100644
--- a/Libraries/LibWeb/CSS/StyleSheetState.cpp
+++ b/Libraries/LibWeb/CSS/StyleSheetState.cpp
@@ -45,7 +45,7 @@ NonnullRefPtr<StyleSheetState> StyleSheetState::create(RustRuleList rules, GC::P
WebIDL::ExceptionOr<NonnullRefPtr<StyleSheetState>> StyleSheetState::create_constructed(DOM::Document const& associated_document, CSSStyleSheetOptions const& options)
{
// 1. Construct a new CSSStyleSheet object sheet.
- auto media = options.media.has<GC::Ref<MediaList>>() ? options.media.get<GC::Ref<MediaList>>()->native_list().share() : RustMediaList {};
+ auto media = options.media.has<GC::Ref<MediaList>>() ? options.media.get<GC::Ref<MediaList>>()->share_native_list() : RustMediaList {};
auto sheet = create(RustRuleList {}, const_cast<DOM::Document*>(&associated_document), move(media), {});
// 2. Set sheet’s location to the base URL of the associated Document for the current principal global object.
@@ -935,7 +935,7 @@ GC::Ref<MediaList> StyleSheetState::media() const
if (auto* import = owner_import())
return import->media();
if (!m_media) {
- m_media = MediaList::create(native_media_list().retain());
+ m_media = MediaList::create(native_media_list());
m_media->set_associated_style_sheet(const_cast<StyleSheetState&>(*this));
}
return *m_media;
diff --git a/Libraries/LibWeb/Rust/src/css/media_list.rs b/Libraries/LibWeb/Rust/src/css/media_list.rs
index 05d279414ec..b0ebef9a7a0 100644
--- a/Libraries/LibWeb/Rust/src/css/media_list.rs
+++ b/Libraries/LibWeb/Rust/src/css/media_list.rs
@@ -4,6 +4,8 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+use ak::Utf16StringUnits;
+
use crate::css::css_tokenizer::TokenizerInput;
use crate::css::ffi_support::{FfiUtf16View, OwnedBox};
use crate::css::parser::query_parser::{
@@ -40,6 +42,12 @@ struct MediaListState {
matches: Vec<bool>,
}
+pub enum MediaListDeleteResult {
+ Invalid,
+ Removed,
+ NotFound,
+}
+
#[derive(Clone)]
pub struct MediaList {
owner: Rc<RefCell<MediaListState>>,
@@ -50,10 +58,90 @@ impl MediaList {
self.owner.borrow().data.clone()
}
- pub(crate) fn share(&self) -> Self {
+ /// A list of its own with the media queries of this one, as they are now.
+ pub fn share(&self) -> Self {
Self::new(self.owner.borrow().data.clone())
}
+ /// The number of media queries in the collection of media queries.
+ pub fn length(&self) -> usize {
+ self.owner.borrow().data.queries.len()
+ }
+
+ /// The serialization of the collection of media queries.
+ pub fn media_text(&self) -> Vec<u16> {
+ let state = self.owner.borrow();
+ let mut text = Vec::new();
+ for (index, query) in state.data.queries.iter().enumerate() {
+ if index != 0 {
+ text.extend([u16::from(b','), u16::from(b' ')]);
+ }
+ text.extend(query.media_text());
+ }
+ text
+ }
+
+ /// The serialization of the media query at the index of the collection of media queries, if it has one there.
+ pub fn item(&self, index: usize) -> Option<Vec<u16>> {
+ self.owner
+ .borrow()
+ .data
+ .queries
+ .get(index)
+ .map(|query| query.media_text())
+ }
+
+ /// Replaces the collection of media queries with the result of parsing the text.
+ pub fn set_media_text(&self, text: Utf16StringUnits<'_>) {
+ self.set_text(text.into());
+ }
+
+ /// Whether the medium was added.
+ pub fn append_medium(&self, medium: Utf16StringUnits<'_>) -> bool {
+ // https://drafts.csswg.org/cssom/#dom-medialist-appendmedium
+ // 1. Let m be the result of parsing the given value.
+ // 2. If m is null, then return.
+ let Some(query) = parse_medium(medium.into()) else {
+ return false;
+ };
+ // 3. If comparing m with any of the media queries in the collection of media queries returns true, then return.
+ let text = query.media_text();
+ let mut state = self.owner.borrow_mut();
+ if state.data.queries.iter().any(|existing| existing.media_text() == text) {
+ return false;
+ }
+ // 4. Append m to the collection of media queries.
+ Arc::make_mut(&mut state.data).queries.push(query);
+ state.matches.push(false);
+ true
+ }
+
+ pub fn delete_medium(&self, medium: Utf16StringUnits<'_>) -> MediaListDeleteResult {
+ // https://drafts.csswg.org/cssom/#dom-medialist-deletemedium
+ // 1. Let m be the result of parsing the given value.
+ // 2. If m is null, then return.
+ let Some(query) = parse_medium(medium.into()) else {
+ return MediaListDeleteResult::Invalid;
+ };
+ // 3. Remove any media query from the collection of media queries for which comparing the media query with m
+ // returns true. If nothing was removed, then throw a NotFoundError exception.
+ let text = query.media_text();
+ let mut state = self.owner.borrow_mut();
+ let mut removed = false;
+ for index in (0..state.data.queries.len()).rev() {
+ if state.data.queries[index].media_text() == text {
+ Arc::make_mut(&mut state.data).queries.remove(index);
+ state.matches.remove(index);
+ removed = true;
+ }
+ }
+ if removed {
+ MediaListDeleteResult::Removed
+ } else {
+ MediaListDeleteResult::NotFound
+ }
+ }
+
pub(crate) fn set_text(&self, source: TokenizerInput<'_>) {
let data = Arc::new(parse(source));
*self.owner.borrow_mut() = MediaListState {
@@ -126,7 +214,7 @@ pub extern "C" fn rust_media_list_free(list: OwnedBox<MediaList>) {
#[unsafe(no_mangle)]
pub extern "C" fn rust_media_list_length(list: &MediaList) -> usize {
- list.owner.borrow().data.queries.len()
+ list.length()
}
#[unsafe(no_mangle)]
@@ -134,74 +222,13 @@ pub extern "C" fn rust_media_list_set_text(list: &MediaList, source: FfiUtf16Vie
list.set_text(source.units().unwrap());
}
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_media_list_append(list: &MediaList, source: FfiUtf16View) -> bool {
- // https://drafts.csswg.org/cssom/#dom-medialist-appendmedium
- // 1. Let m be the result of parsing the given value.
- // 2. If m is null, then return.
- let Some(query) = parse_medium(source.units().unwrap()) else {
- return false;
- };
- // 3. If comparing m with any of the media queries in the collection of media queries returns true, then return.
- let text = query.media_text();
- let mut state = list.owner.borrow_mut();
- if state.data.queries.iter().any(|existing| existing.media_text() == text) {
- return false;
- }
- // 4. Append m to the collection of media queries.
- Arc::make_mut(&mut state.data).queries.push(query);
- state.matches.push(false);
- true
-}
-
-#[repr(u8)]
-pub enum MediaListDeleteResult {
- Invalid,
- Removed,
- NotFound,
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_media_list_delete(list: &MediaList, source: FfiUtf16View) -> MediaListDeleteResult {
- // https://drafts.csswg.org/cssom/#dom-medialist-deletemedium
- // 1. Let m be the result of parsing the given value.
- // 2. If m is null, then return.
- let Some(query) = parse_medium(source.units().unwrap()) else {
- return MediaListDeleteResult::Invalid;
- };
- // 3. Remove any media query from the collection of media queries for which comparing the media query with m
- // returns true. If nothing was removed, then throw a NotFoundError exception.
- let text = query.media_text();
- let mut state = list.owner.borrow_mut();
- let mut removed = false;
- for index in (0..state.data.queries.len()).rev() {
- if state.data.queries[index].media_text() == text {
- Arc::make_mut(&mut state.data).queries.remove(index);
- state.matches.remove(index);
- removed = true;
- }
- }
- if removed {
- MediaListDeleteResult::Removed
- } else {
- MediaListDeleteResult::NotFound
- }
-}
-
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_media_list_serialize(
list: &MediaList,
context: *mut c_void,
visit: VisitQuerySerialization,
) {
- let state = list.owner.borrow();
- let mut text = Vec::new();
- for (index, query) in state.data.queries.iter().enumerate() {
- if index != 0 {
- text.extend([u16::from(b','), u16::from(b' ')]);
- }
- text.extend(query.media_text());
- }
+ let text = list.media_text();
unsafe { visit(context, text.as_ptr(), text.len()) };
}
@@ -212,11 +239,9 @@ pub unsafe extern "C" fn rust_media_list_item(
context: *mut c_void,
visit: VisitQuerySerialization,
) -> bool {
- let state = list.owner.borrow();
- let Some(query) = state.data.queries.get(index) else {
+ let Some(text) = list.item(index) else {
return false;
};
- let text = query.media_text();
unsafe { visit(context, text.as_ptr(), text.len()) };
true
}
diff --git a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/ownership_tests.rs b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/ownership_tests.rs
index 2f92bcca5a1..56b51468350 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/ownership_tests.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/ownership_tests.rs
@@ -1148,25 +1148,25 @@ fn media_mutation_preserves_live_owners_and_shared_snapshots() {
assert!(rust_media_list_matches(&retained));
assert!(!rust_media_list_matches(&shared));
assert!(matches!(
- rust_media_list_delete(&media, view(&utf16("all"))),
+ media.delete_medium(ak::Utf16StringUnits::Utf16(&utf16("all"))),
MediaListDeleteResult::Removed
));
assert!(!rust_media_list_matches(&media));
assert_eq!(text(&retained), utf16("print"));
assert_eq!(text(&shared), utf16("all, print"));
- assert!(!rust_media_list_append(&media, view(&utf16("PRINT"))));
- assert!(!rust_media_list_append(&media, view(&utf16("screen, print"))));
+ assert!(!media.append_medium(ak::Utf16StringUnits::Utf16(&utf16("PRINT"))));
+ assert!(!media.append_medium(ak::Utf16StringUnits::Utf16(&utf16("screen, print"))));
assert!(matches!(
- rust_media_list_delete(&media, view(&utf16("screen, print"))),
+ media.delete_medium(ak::Utf16StringUnits::Utf16(&utf16("screen, print"))),
MediaListDeleteResult::Invalid
));
assert!(matches!(
- rust_media_list_delete(&media, view(&utf16("screen"))),
+ media.delete_medium(ak::Utf16StringUnits::Utf16(&utf16("screen"))),
MediaListDeleteResult::NotFound
));
rust_media_list_set_text(&media, view(&utf16("écran, écran")));
assert!(matches!(
- rust_media_list_delete(&media, view(&utf16("écran"))),
+ media.delete_medium(ak::Utf16StringUnits::Utf16(&utf16("écran"))),
MediaListDeleteResult::Removed
));
assert_eq!(rust_media_list_length(&retained), 0);
@@ -1178,7 +1178,7 @@ fn media_mutation_preserves_live_owners_and_shared_snapshots() {
(&raw mut item).cast(),
collect_text
));
- assert!(rust_media_list_append(&media, view(&utf16(""))));
+ assert!(media.append_medium(ak::Utf16StringUnits::Utf16(&utf16(""))));
assert!(rust_media_list_item(&retained, 0, (&raw mut item).cast(), collect_text));
assert_eq!(item, utf16("not all"));
drop(media);
diff --git a/Libraries/LibWeb/Rust/src/lib.rs b/Libraries/LibWeb/Rust/src/lib.rs
index 46675d36979..b5522003a2d 100644
--- a/Libraries/LibWeb/Rust/src/lib.rs
+++ b/Libraries/LibWeb/Rust/src/lib.rs
@@ -33,6 +33,7 @@ pub(crate) mod style_layout_pool;
pub(crate) mod svg;
// What libweb_bindings_rust, whose interfaces are implemented in Rust, uses of this crate.
+pub use css::media_list::{MediaList as NativeMediaList, MediaListDeleteResult};
pub use svg::gfx_path_from_path_data;
/// The red, green, blue and alpha of a CSS <color> in ASCII that needs nothing to be resolved against, or None for any