Truly independent web browser
LibWeb: Implement WebVTT in Rust
Shannon Booth6c72979ff4f4
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rsindex 31e485d936c..6178f694599 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs@@ -9,6 +9,7 @@//! Libraries/LibWeb/HTML/MessagePort.cpp declare. A cell is the cell of an object of the interface that the name of//! the function says. Libraries/LibWeb/HTML/BroadcastChannel.cpp hands the BroadcastChannel objects the messages that//! other processes post, and Libraries/LibWeb/HTML/Window.cpp runs the window post message steps.+//! Libraries/LibWeb/HTML/TextTrackCue.cpp reads and updates the TextTrackCue objects that its text tracks hold.use core::ffi::{c_int, c_void};use core::ptr::NonNull;@@ -25,6 +26,7 @@ use super::image_data::ImageData;use super::message_port::MessagePort;use super::storage::{Storage, StorageType};use super::storage_event::{StorageEvent, StorageEventInit};+use super::text_track_cue::AnyTextTrackCue;use super::window::{PostedMessage, queue_posted_message, window_post_message_steps};use super::window_or_worker_global_scope::structured_clone;use crate::bindings::CallContext;@@ -736,3 +738,120 @@ pub unsafe extern "C" fn web_image_bitmap_rendering_context_alpha(context: *mut// SAFETY: The caller passes a live cell.unsafe { object_from_abi::<ImageBitmapRenderingContext>(context) }.alpha()}++/// # Safety+///+/// `cue` must be the live cell of a TextTrackCue.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_text_track_cue_event_target(cue: *mut c_void) -> *mut c_void {+ // SAFETY: The caller passes a live cell.+ unsafe { AnyTextTrackCue::from_abi(cue) }.event_target().as_ptr()+}++/// The cell of the TextTrack whose list of cues the cue is in, or null.+///+/// # Safety+///+/// `cue` must be the live cell of a TextTrackCue.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_text_track_cue_track(cue: *mut c_void) -> *mut c_void {+ // SAFETY: The caller passes a live cell.+ let cue = unsafe { AnyTextTrackCue::from_abi(cue) };+ cue.track_cell().map_or(core::ptr::null_mut(), |track| track.as_ptr())+}++/// # Safety+///+/// `cue` must be the live cell of a TextTrackCue, and `track` a live TextTrack or null.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_text_track_cue_set_track(cue: *mut c_void, track: *mut c_void) {+ // SAFETY: The caller passes a live cell.+ let cue = unsafe { AnyTextTrackCue::from_abi(cue) };+ // SAFETY: The caller passes a live TextTrack, or null.+ let track = (!track.is_null()).then(|| unsafe { CppCell::from_raw(track) });+ cue.set_track_cell(track);+}++/// The identifier of the cue, whose reference the caller adopts.+///+/// # Safety+///+/// `cue` must be the live cell of a TextTrackCue.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_text_track_cue_id(cue: *mut c_void) -> usize {+ // SAFETY: The caller passes a live cell.+ unsafe { AnyTextTrackCue::from_abi(cue) }.identifier().into_raw()+}++/// # Safety+///+/// `cue` must be the live cell of a TextTrackCue, and `id` a string that the caller lends for the call.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_text_track_cue_set_id(cue: *mut c_void, id: usize) {+ // SAFETY: The caller passes a live cell and lends the string.+ let (cue, id) = unsafe { (AnyTextTrackCue::from_abi(cue), Utf16String::from_raw_borrowed(id)) };+ cue.set_identifier(id);+}++/// # Safety+///+/// `cue` must be the live cell of a TextTrackCue.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_text_track_cue_start_time(cue: *mut c_void) -> f64 {+ // SAFETY: The caller passes a live cell.+ unsafe { AnyTextTrackCue::from_abi(cue) }.start_time_value()+}++/// # Safety+///+/// `cue` must be the live cell of a TextTrackCue.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_text_track_cue_end_time(cue: *mut c_void) -> f64 {+ // SAFETY: The caller passes a live cell.+ unsafe { AnyTextTrackCue::from_abi(cue) }.end_time_value()+}++/// # Safety+///+/// `cue` must be the live cell of a TextTrackCue.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_text_track_cue_pause_on_exit(cue: *mut c_void) -> bool {+ // SAFETY: The caller passes a live cell.+ unsafe { AnyTextTrackCue::from_abi(cue) }.pause_on_exit_flag()+}++/// # Safety+///+/// `cue` must be the live cell of a TextTrackCue.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_text_track_cue_is_active(cue: *mut c_void) -> bool {+ // SAFETY: The caller passes a live cell.+ unsafe { AnyTextTrackCue::from_abi(cue) }.is_active()+}++/// # Safety+///+/// `cue` must be the live cell of a TextTrackCue.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_text_track_cue_set_active(cue: *mut c_void, active: bool) {+ // SAFETY: The caller passes a live cell.+ unsafe { AnyTextTrackCue::from_abi(cue) }.set_active(active);+}++/// # Safety+///+/// `cue` must be the live cell of a TextTrackCue.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_text_track_cue_order_added(cue: *mut c_void) -> u64 {+ // SAFETY: The caller passes a live cell.+ unsafe { AnyTextTrackCue::from_abi(cue) }.order_added()+}++/// # Safety+///+/// `cue` must be the live cell of a TextTrackCue.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_text_track_cue_set_order_added(cue: *mut c_void, order_added: u64) {+ // SAFETY: The caller passes a live cell.+ unsafe { AnyTextTrackCue::from_abi(cue) }.set_order_added(order_added);+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rsindex ab8f38f98e1..13800cf04c6 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs@@ -7,7 +7,8 @@//! The 2D canvas contexts, with the attributes and operations of each of their mixins in the module of its IDL file,//! the objects that they draw with, the images that they and WebGL read and write the pixels of, and the operations of//! a path that Path2D and the contexts share. The state that the contexts share is in crate::canvas_2d. The message-//! ports and channels of web messaging, the broadcast channels and Web Storage are here as well.+//! ports and channels of web messaging, the broadcast channels, Web Storage and the cues of text tracks are here as+//! well.pub(crate) mod canvas_path;pub(crate) mod color_stops;@@ -97,6 +98,8 @@ pub(crate) mod structured_serialize;#[cfg(not(test))]pub(crate) mod text_metrics;#[cfg(not(test))]+pub(crate) mod text_track_cue;+#[cfg(not(test))]pub(crate) mod visibility_state;#[cfg(not(test))]pub(crate) mod visibility_state_entry;diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/text_track_cue.rs b/Libraries/LibWeb/Bindings/Rust/src/html/text_track_cue.rsnew file mode 100644index 00000000000..a861fbf5b3a--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/html/text_track_cue.rs@@ -0,0 +1,252 @@+/*+ * Copyright (c) 2024, Jamie Mansfield <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! TextTrackCue, https://html.spec.whatwg.org/multipage/media.html#texttrackcue++use core::cell::{Cell, RefCell};+use core::ffi::c_void;+use core::ops::Deref;+use core::ptr::NonNull;++use ak::Utf16String;+use libjs_rust::api::{GcRefCell, Trace};++use crate::bindings::conversions::CppInterface;+use crate::bindings::cpp_cell::CppCell;+use crate::bindings::event_target::{CppEventTarget, GetTheParent};+use crate::bindings::interface::{Inherits, Ref, Wrappable, cell_from_abi, cell_if_abi};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::css::css_rule::wrap_cpp_cell;+use crate::web_vtt::vtt_cue::VTTCue;++unsafe extern "C" {+ fn web_html_text_track_cue_timing_changed(track: *mut c_void);+}++// https://html.spec.whatwg.org/multipage/media.html#texttrackcue+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct TextTrackCue {+ event_target: CppEventTarget,++ // The TextTrack whose text track list of cues the cue is in, if any.+ track: GcRefCell<Option<CppCell>>,++ // https://html.spec.whatwg.org/multipage/media.html#text-track-cue-identifier+ #[gc(untraced)]+ identifier: RefCell<Utf16String>,++ // https://html.spec.whatwg.org/multipage/media.html#text-track-cue-start-time+ start_time: Cell<f64>,++ // https://html.spec.whatwg.org/multipage/media.html#text-track-cue-end-time+ end_time: Cell<f64>,++ // https://html.spec.whatwg.org/multipage/media.html#text-track-cue-pause-on-exit-flag+ pause_on_exit: Cell<bool>,++ // https://html.spec.whatwg.org/multipage/media.html#text-track-cue-active-flag+ active: Cell<bool>,++ order_added: Cell<u64>,+}++impl Wrappable for TextTrackCue {+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {+ self.event_target.as_cpp_parent()+ }+}++impl GetTheParent for TextTrackCue {+ fn get_the_parent(&self) -> Option<CppEventTarget> {+ None+ }+}++impl TextTrackCue {+ pub(crate) fn new(start_time: f64, end_time: f64) -> Self {+ Self {+ event_target: CppEventTarget::new(),+ track: GcRefCell::new(None),+ identifier: RefCell::new(Utf16String::from_utf8("")),+ start_time: Cell::new(start_time),+ end_time: Cell::new(end_time),+ pause_on_exit: Cell::new(false),+ active: Cell::new(false),+ order_added: Cell::new(0),+ }+ }++ pub(crate) fn event_target(&self) -> &CppEventTarget {+ &self.event_target+ }++ pub(crate) fn track_cell(&self) -> Option<CppCell> {+ self.track.borrow().clone()+ }++ pub(crate) fn set_track_cell(&self, track: Option<CppCell>) {+ self.track.replace(track);+ }++ pub(crate) fn identifier(&self) -> Utf16String {+ self.identifier.borrow().clone()+ }++ pub(crate) fn set_identifier(&self, identifier: Utf16String) {+ *self.identifier.borrow_mut() = identifier;+ }++ pub(crate) fn start_time_value(&self) -> f64 {+ self.start_time.get()+ }++ pub(crate) fn end_time_value(&self) -> f64 {+ self.end_time.get()+ }++ pub(crate) fn pause_on_exit_flag(&self) -> bool {+ self.pause_on_exit.get()+ }++ pub(crate) fn is_active(&self) -> bool {+ self.active.get()+ }++ pub(crate) fn set_active(&self, active: bool) {+ self.active.set(active);+ }++ pub(crate) fn order_added(&self) -> u64 {+ self.order_added.get()+ }++ pub(crate) fn set_order_added(&self, order_added: u64) {+ self.order_added.set(order_added);+ }++ fn timing_changed(&self) {+ let Some(track) = self.track_cell() else {+ return;+ };+ // SAFETY: The TextTrack is live, which the cue keeps alive.+ unsafe { web_html_text_track_cue_timing_changed(track.as_ptr()) };+ }++ // https://html.spec.whatwg.org/multipage/media.html#dom-texttrackcue-track+ pub(crate) fn track(&self, cx: &mut CallContext) -> WebIdlResult<Option<CppInterface>> {+ // The track attribute, on getting, must return the TextTrack object of the text track in whose list of cues the+ // text track cue that the TextTrackCue object represents finds itself, if any; or null otherwise.+ Ok(self.track_cell().map(|track| wrap_cpp_cell(cx, &track)))+ }++ // https://html.spec.whatwg.org/multipage/media.html#dom-texttrackcue-id+ pub(crate) fn id(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {+ // The id attribute, on getting, must return the text track cue identifier of the text track cue that the+ // TextTrackCue object represents.+ Ok(self.identifier())+ }++ // https://html.spec.whatwg.org/multipage/media.html#dom-texttrackcue-id+ pub(crate) fn set_id(&self, _: &mut CallContext, value: Utf16String) -> WebIdlResult<()> {+ // On setting, the text track cue identifier must be set to the new value.+ self.set_identifier(value);+ Ok(())+ }++ // https://html.spec.whatwg.org/multipage/media.html#dom-texttrackcue-starttime+ pub(crate) fn start_time(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ // The startTime attribute, on getting, must return the text track cue start time of the text track cue that the+ // TextTrackCue object represents, in seconds.+ Ok(self.start_time.get())+ }++ // https://html.spec.whatwg.org/multipage/media.html#dom-texttrackcue-starttime+ pub(crate) fn set_start_time(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // On setting, the text track cue start time must be set to the new value, interpreted in seconds; then, if the+ // TextTrackCue object's text track cue is in a text track's list of cues, and that text track is in a media+ // element's list of text tracks, and the media element's show poster flag is not set, then run the time marches+ // on steps for that media element.+ self.start_time.set(value);+ self.timing_changed();+ Ok(())+ }++ // https://html.spec.whatwg.org/multipage/media.html#dom-texttrackcue-endtime+ pub(crate) fn end_time(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ // The endTime attribute, on getting, must return the text track cue end time of the text track cue that the+ // TextTrackCue object represents, in seconds.+ Ok(self.end_time.get())+ }++ // https://html.spec.whatwg.org/multipage/media.html#dom-texttrackcue-endtime+ pub(crate) fn set_end_time(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // On setting, if the new value is negative Infinity or a Not-a-Number (NaN) value, then throw a TypeError+ // exception.+ if value == f64::NEG_INFINITY || value.is_nan() {+ return Err(Exception::type_error("Value is negative infinity or NaN"));+ }++ // Otherwise, the text track cue end time must be set to the new value.+ self.end_time.set(value);++ // Then, if the TextTrackCue object's text track cue is in a text track's list of cues, and that text track is+ // in a media element's list of text tracks, and the media element's show poster flag is not set, then run the+ // time marches on steps for that media element.+ self.timing_changed();+ Ok(())+ }++ // https://html.spec.whatwg.org/multipage/media.html#dom-texttrackcue-pauseonexit+ pub(crate) fn pause_on_exit(&self, _: &mut CallContext) -> WebIdlResult<bool> {+ // The pauseOnExit attribute, on getting, must return true if the text track cue pause-on-exit flag of the text+ // track cue that the TextTrackCue object represents is set; or false otherwise.+ Ok(self.pause_on_exit.get())+ }++ // https://html.spec.whatwg.org/multipage/media.html#dom-texttrackcue-pauseonexit+ pub(crate) fn set_pause_on_exit(&self, _: &mut CallContext, value: bool) -> WebIdlResult<()> {+ // On setting, the text track cue pause-on-exit flag must be set if the new value is true, and must be unset+ // otherwise.+ self.pause_on_exit.set(value);+ Ok(())+ }+}++/// An object of TextTrackCue or of an interface that inherits from it, as LibWeb's C++ code names it.+pub(crate) enum AnyTextTrackCue {+ TextTrackCue(Ref<TextTrackCue>),+ VTTCue(Ref<VTTCue>),+}++impl Deref for AnyTextTrackCue {+ type Target = TextTrackCue;++ fn deref(&self) -> &TextTrackCue {+ match self {+ Self::TextTrackCue(cue) => cue,+ Self::VTTCue(cue) => {+ let cue: &VTTCue = cue;+ cue.parent()+ }+ }+ }+}++impl AnyTextTrackCue {+ /// # Safety+ ///+ /// `cell` must be the live cell of an object of TextTrackCue or of an interface that inherits from it.+ pub(crate) unsafe fn from_abi(cell: *mut c_void) -> Self {+ // SAFETY: The caller passes a live cell.+ if let Some(cue) = unsafe { cell_if_abi::<VTTCue>(cell) } {+ return Self::VTTCue(cue);+ }+ // SAFETY: The caller passes the live cell of a TextTrackCue, which is no VTTCue.+ Self::TextTrackCue(unsafe { cell_from_abi::<TextTrackCue>(cell) })+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rsindex 235fd69ac46..70b69dc336d 100644--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs@@ -397,6 +397,16 @@ pub(crate) mod web_gl;)]pub(crate) mod web_locks;#[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 web_vtt;+#[cfg(not(test))]pub(crate) mod webidl;#[cfg(not(test))]pub(crate) mod webrtc;diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_vtt/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/web_vtt/exports.rsnew file mode 100644index 00000000000..ff9fa510e41--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/web_vtt/exports.rs@@ -0,0 +1,66 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The C ABI through which LibWeb's C++ code parses WebVTT files and creates VTTCue objects for the cues in them,+//! which Libraries/LibWeb/WebVTT/Parser.cpp and Libraries/LibWeb/WebVTT/VTTCue.cpp declare.++use core::ffi::c_void;++use ak::Utf16String;+use libjs_rust::api::Vm;++use crate::bindings::interface::cell_into_abi;+use crate::web_vtt::parser::parse_webvtt_file;+use crate::web_vtt::vtt_cue::VTTCue;++/// https://w3c.github.io/webvtt/#dom-vttcue-vttcue+///+/// # Safety+///+/// `vm` must be the live VM, and `text` a string that the caller lends for the call.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_vtt_cue_create(+ vm: *mut c_void,+ start_time: f64,+ end_time: f64,+ text: usize,+) -> *mut c_void {+ // SAFETY: The caller passes the live VM and lends the string.+ let (vm, text) = unsafe { (&*vm.cast::<Vm>(), Utf16String::from_raw_borrowed(text)) };+ let Ok(cue) = VTTCue::create(vm, start_time, end_time, text) else {+ unreachable!("C++ creates cues whose end time is neither negative infinity nor NaN");+ };+ cell_into_abi(cue)+}++/// https://w3c.github.io/webvtt/#webvtt-parser+///+/// Parses the bytes and passes each cue to `on_cue`, with the identifier and the text, whose references the callee+/// adopts. Returns false if the file does not start with the WebVTT file signature.+///+/// # Safety+///+/// `bytes` must point to `length` bytes, and `on_cue` must be safe to call with `ctx`.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_vtt_parse_webvtt_file(+ bytes: *const u8,+ length: usize,+ ctx: *mut c_void,+ on_cue: unsafe extern "C" fn(ctx: *mut c_void, identifier: usize, start_time: f64, end_time: f64, text: usize),+) -> bool {+ // SAFETY: The caller passes `length` bytes.+ let bytes = unsafe { ak::slice_from_raw_parts(bytes, length) };+ let Some(cues) = parse_webvtt_file(bytes) else {+ return false;+ };+ for cue in cues {+ let identifier = cue.identifier.into_raw();+ let text = cue.text.into_raw();+ // SAFETY: The caller passes a callback that is safe to call with the context.+ unsafe { on_cue(ctx, identifier, cue.start_time, cue.end_time, text) };+ }+ true+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_vtt/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/web_vtt/mod.rsnew file mode 100644index 00000000000..3fe749c945f--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/web_vtt/mod.rs@@ -0,0 +1,12 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! WebVTT: The Web Video Text Tracks Format, https://w3c.github.io/webvtt/++pub(crate) mod exports;+pub(crate) mod parser;+pub(crate) mod vtt_cue;+pub(crate) mod vtt_region;diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_vtt/parser.rs b/Libraries/LibWeb/Bindings/Rust/src/web_vtt/parser.rsnew file mode 100644index 00000000000..ddbd6e7ebd0--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/web_vtt/parser.rs@@ -0,0 +1,483 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The WebVTT parser, https://w3c.github.io/webvtt/#webvtt-parser++use ak::character_types::is_ascii_digit;+use ak::{GenericLexer, Utf16String};+use libwebcommon_rust::infra::character_types::is_ascii_whitespace;++const LINE_FEED: u16 = b'\n' as u16;+const CARRIAGE_RETURN: u16 = b'\r' as u16;+const REPLACEMENT_CHARACTER: u16 = 0xFFFD;++/// A cue that the parser collected, which LibWeb creates a VTTCue for.+pub(crate) struct ParsedCue {+ pub(crate) identifier: Utf16String,+ pub(crate) start_time: f64,+ pub(crate) end_time: f64,+ pub(crate) text: Utf16String,+}++fn contains(haystack: &[u16], needle: &[u16]) -> bool {+ haystack.windows(needle.len()).any(|window| window == needle)+}++fn utf16(string: &str) -> Vec<u16> {+ string.encode_utf16().collect()+}++fn skip_whitespace(lexer: &mut GenericLexer<'_, u16>) {+ lexer.ignore_while(|code_unit| is_ascii_whitespace(code_unit.into()));+}++fn collect_ascii_digits<'a>(lexer: &mut GenericLexer<'a, u16>) -> &'a [u16] {+ lexer.consume_while(|code_unit| is_ascii_digit(code_unit.into()))+}++fn interpret_as_base_ten_integer(digits: &[u16]) -> u64 {+ digits.iter().fold(0u64, |value, digit| {+ value.wrapping_mul(10).wrapping_add(u64::from(digit - u16::from(b'0')))+ })+}++// https://w3c.github.io/webvtt/#collect-a-webvtt-timestamp+fn collect_a_webvtt_timestamp(lexer: &mut GenericLexer<'_, u16>) -> Option<f64> {+ // 1. Let input and position be the same variables as those of the same name in the algorithm that invoked these+ // steps.++ // 2. Let most significant units be minutes.+ let mut most_significant_units_are_hours = false;++ // 3. If position is past the end of input, return an error and abort these steps.+ let code_unit = lexer.peek()?;++ // 4. If the character indicated by position is not an ASCII digit, then return an error and abort these steps.+ if !is_ascii_digit(code_unit.into()) {+ return None;+ }++ // 5. Collect a sequence of code points that are ASCII digits, and let string be the collected substring.+ let mut string = collect_ascii_digits(lexer);++ // 6. Interpret string as a base-ten integer. Let value1 be that integer.+ let mut value1 = interpret_as_base_ten_integer(string);++ // 7. If string is not exactly two characters in length, or if value1 is greater than 59, let most significant units+ // be hours.+ if string.len() != 2 || value1 > 59 {+ most_significant_units_are_hours = true;+ }++ // 8. If position is beyond the end of input or if the character at position is not a U+003A COLON character (:),+ // then return an error and abort these steps. Otherwise, move position forwards one character.+ if !lexer.consume_specific(u16::from(b':')) {+ return None;+ }++ // 9. Collect a sequence of code points that are ASCII digits, and let string be the collected substring.+ string = collect_ascii_digits(lexer);++ // 10. If string is not exactly two characters in length, return an error and abort these steps.+ if string.len() != 2 {+ return None;+ }++ // 11. Interpret string as a base-ten integer. Let value2 be that integer.+ let mut value2 = interpret_as_base_ten_integer(string);+ let value3;++ // 12. If most significant units is hours, or if position is not beyond the end of input and the character at+ // position is a U+003A COLON character (:), run these substeps:+ if most_significant_units_are_hours || lexer.peek() == Some(u16::from(b':')) {+ // 1. If position is beyond the end of input or if the character at position is not a U+003A COLON character+ // (:), then return an error and abort these steps. Otherwise, move position forwards one character.+ if !lexer.consume_specific(u16::from(b':')) {+ return None;+ }++ // 2. Collect a sequence of code points that are ASCII digits, and let string be the collected substring.+ string = collect_ascii_digits(lexer);++ // 3. If string is not exactly two characters in length, return an error and abort these steps.+ if string.len() != 2 {+ return None;+ }++ // 4. Interpret string as a base-ten integer. Let value3 be that integer.+ value3 = interpret_as_base_ten_integer(string);+ }+ // Otherwise (if most significant units is not hours, and either position is beyond the end of input, or the+ // character at position is not a U+003A COLON character (:)), let value3 have the value of value2, then value2 have+ // the value of value1, then let value1 equal zero.+ else {+ value3 = value2;+ value2 = value1;+ value1 = 0;+ }++ // 13. If position is beyond the end of input or if the character at position is not a U+002E FULL STOP character+ // (.), then return an error and abort these steps. Otherwise, move position forwards one character.+ if !lexer.consume_specific(u16::from(b'.')) {+ return None;+ }++ // 14. Collect a sequence of code points that are ASCII digits, and let string be the collected substring.+ string = collect_ascii_digits(lexer);++ // 15. If string is not exactly three characters in length, return an error and abort these steps.+ if string.len() != 3 {+ return None;+ }++ // 16. Interpret string as a base-ten integer. Let value4 be that integer.+ let value4 = interpret_as_base_ten_integer(string);++ // 17. If value2 is greater than 59 or if value3 is greater than 59, return an error and abort these steps.+ if value2 > 59 || value3 > 59 {+ return None;+ }++ // 18. Let result be value1×60×60 + value2×60 + value3 + value4∕1000.+ let result = (value1 as f64 * 60.0 * 60.0) + (value2 as f64 * 60.0) + value3 as f64 + (value4 as f64 / 1000.0);++ // 19. Return result.+ Some(result)+}++// https://w3c.github.io/webvtt/#collect-webvtt-cue-timings-and-settings+fn collect_webvtt_cue_timings_and_settings(input: &[u16], cue: &mut ParsedCue) -> bool {+ // 1. Let input be the string being parsed.+ // 2. Let position be a pointer into input, initially pointing at the start of the string.+ let mut lexer = GenericLexer::new(input);++ // 3. Skip whitespace.+ skip_whitespace(&mut lexer);++ // 4. Collect a WebVTT timestamp. If that algorithm fails, then abort these steps and return failure. Otherwise, let+ // cue's text track cue start time be the collected time.+ let Some(start_time) = collect_a_webvtt_timestamp(&mut lexer) else {+ return false;+ };+ cue.start_time = start_time;++ // 5. Skip whitespace.+ skip_whitespace(&mut lexer);++ // 6. If the character at position is not a U+002D HYPHEN-MINUS character (-) then abort these steps and return+ // failure. Otherwise, move position forwards one character.+ // 7. If the character at position is not a U+002D HYPHEN-MINUS character (-) then abort these steps and return+ // failure. Otherwise, move position forwards one character.+ // 8. If the character at position is not a U+003E GREATER-THAN SIGN character (>) then abort these steps and return+ // failure. Otherwise, move position forwards one character.+ if !lexer.consume_specific(u16::from(b'-'))+ || !lexer.consume_specific(u16::from(b'-'))+ || !lexer.consume_specific(u16::from(b'>'))+ {+ return false;+ }++ // 9. Skip whitespace.+ skip_whitespace(&mut lexer);++ // 10. Collect a WebVTT timestamp. If that algorithm fails, then abort these steps and return failure. Otherwise, let+ // cue's text track cue end time be the collected time.+ let Some(end_time) = collect_a_webvtt_timestamp(&mut lexer) else {+ return false;+ };+ cue.end_time = end_time;++ // FIXME: 11. Let remainder be the trailing substring of input starting at position.+ // FIXME: 12. Parse the WebVTT cue settings from remainder using regions for cue.+ true+}++fn is_block_keyword(buffer: &[u16], keyword: &str) -> bool {+ let keyword = utf16(keyword);+ let Some(remainder) = buffer.strip_prefix(keyword.as_slice()) else {+ return false;+ };+ remainder.iter().all(|&code_unit| is_ascii_whitespace(code_unit.into()))+}++struct Parser<'a> {+ input: &'a [u16],+ lexer: GenericLexer<'a, u16>,+ seen_cue: bool,+}++impl<'a> Parser<'a> {+ fn new(input: &'a [u16]) -> Self {+ Self {+ input,+ lexer: GenericLexer::new(input),+ seen_cue: false,+ }+ }++ fn collect_a_sequence_of_code_points_that_are_not_line_feeds(&mut self) -> &'a [u16] {+ self.lexer.consume_while(|code_unit| code_unit != LINE_FEED)+ }++ fn collect_a_sequence_of_line_feeds(&mut self) {+ self.lexer.ignore_while(|code_unit| code_unit == LINE_FEED);+ }++ // https://w3c.github.io/webvtt/#collect-a-webvtt-block+ fn collect_a_webvtt_block(&mut self, in_header: bool) -> Option<ParsedCue> {+ // 1. Let input, position, seen cue and regions be the same variables as those of the same name in the algorithm+ // that invoked these steps.++ // 2. Let line count be zero.+ let mut line_count = 0usize;++ // 3. Let previous position be position.+ let mut previous_position = self.lexer.tell();++ // 4. Let line be the empty string.+ // 5. Let buffer be the empty string.+ let mut buffer: Vec<u16> = Vec::new();++ // 6. Let seen EOF be false.+ let mut seen_eof = false;++ // 7. Let seen arrow be false.+ let mut seen_arrow = false;++ // 8. Let cue be null.+ let mut cue: Option<ParsedCue> = None;++ // FIXME: 9. Let stylesheet be null.+ // FIXME: 10. Let region be null.++ let arrow = utf16("-->");++ // 11. Loop: Run these substeps in a loop:+ loop {+ // 1. Collect a sequence of code points that are not U+000A LINE FEED (LF) characters. Let line be those+ // characters, if any.+ let line = self.collect_a_sequence_of_code_points_that_are_not_line_feeds();++ // 2. Increment line count by 1.+ line_count += 1;++ // 3. If position is past the end of input, let seen EOF be true. Otherwise, the character indicated by+ // position is a U+000A LINE FEED (LF) character; advance position to the next character in input.+ if self.lexer.is_eof() {+ seen_eof = true;+ } else {+ self.lexer.ignore(1);+ }++ // 4. If line contains the three-character substring "-->" (U+002D HYPHEN-MINUS, U+002D HYPHEN-MINUS, U+003E+ // GREATER-THAN SIGN), then run these substeps:+ if contains(line, &arrow) {+ // 1. If in header is not set and at least one of the following conditions are true:+ // - line count is 1+ // - line count is 2 and seen arrow is false+ // ...then run these substeps:+ if !in_header && (line_count == 1 || (line_count == 2 && !seen_arrow)) {+ // 1. Let seen arrow be true.+ seen_arrow = true;++ // 2. Let previous position be position.+ previous_position = self.lexer.tell();++ // 3. Cue creation: Let cue be a new WebVTT cue and initialize it as follows:+ // Let cue's text track cue identifier be buffer.+ // FIXME: Initialize the remaining cue fields once cue settings are supported.+ let mut new_cue = ParsedCue {+ identifier: Utf16String::from_utf16(&buffer),+ start_time: 0.0,+ end_time: 0.0,+ text: Utf16String::from_utf8(""),+ };++ // 4. Collect WebVTT cue timings and settings from line using regions for cue. If that fails, let+ // cue be null. Otherwise, let buffer be the empty string and let seen cue be true.+ if collect_webvtt_cue_timings_and_settings(line, &mut new_cue) {+ cue = Some(new_cue);+ buffer.clear();+ self.seen_cue = true;+ } else {+ cue = None;+ }+ }+ // Otherwise, let position be previous position and break out of loop.+ else {+ self.lexer.retreat(self.lexer.tell() - previous_position);+ break;+ }+ }+ // 5. Otherwise, if line is the empty string, break out of loop.+ else if line.is_empty() {+ break;+ }+ // 6. Otherwise, run these substeps:+ else {+ // 1. If in header is not set and line count is 2, run these substeps:+ if !in_header && line_count == 2 {+ // 1. If seen cue is false and buffer starts with the substring "STYLE" (U+0053 LATIN CAPITAL LETTER+ // S, U+0054 LATIN CAPITAL LETTER T, U+0059 LATIN CAPITAL LETTER Y, U+004C LATIN CAPITAL LETTER+ // L, U+0045 LATIN CAPITAL LETTER E), and the remaining characters in buffer (if any) are all+ // ASCII whitespace, then run these substeps:+ // 2. Otherwise, if seen cue is false and buffer starts with the substring "REGION" (U+0052 LATIN+ // CAPITAL LETTER R, U+0045 LATIN CAPITAL LETTER E, U+0047 LATIN CAPITAL LETTER G, U+0049 LATIN+ // CAPITAL LETTER I, U+004F LATIN CAPITAL LETTER O, U+004E LATIN CAPITAL LETTER N), and the+ // remaining characters in buffer (if any) are all ASCII whitespace, then run these substeps:+ if !self.seen_cue && (is_block_keyword(&buffer, "STYLE") || is_block_keyword(&buffer, "REGION")) {+ // FIXME: Create the CSS style sheet or WebVTT region.+ // Let buffer be the empty string.+ buffer.clear();+ }+ }++ // 2. If buffer is not the empty string, append a U+000A LINE FEED (LF) character to buffer.+ if !buffer.is_empty() {+ buffer.push(LINE_FEED);+ }++ // 3. Append line to buffer.+ buffer.extend_from_slice(line);++ // 4. Let previous position be position.+ previous_position = self.lexer.tell();+ }++ // 7. If seen EOF is true, break out of loop.+ if seen_eof {+ break;+ }+ }++ // 12. If cue is not null, let the cue text of cue be buffer, and return cue.+ if let Some(mut cue) = cue {+ cue.text = Utf16String::from_utf16(&buffer);+ return Some(cue);+ }++ // FIXME: 13. Otherwise, if stylesheet is not null, then Parse a stylesheet from buffer. If it returned a list of+ // rules, assign the list as stylesheet's CSS rules; otherwise, set stylesheet's CSS rules to an+ // empty list. Finally, return stylesheet.+ // FIXME: 14. Otherwise, if region is not null, then collect WebVTT region settings from buffer using region for+ // the results. Construct a WebVTT Region Object from region, and return it.++ // 15. Otherwise, return null.+ None+ }++ // https://w3c.github.io/webvtt/#webvtt-parser-algorithm+ fn parse(&mut self) -> Option<Vec<ParsedCue>> {+ let mut output = Vec::new();++ // 2. Let position be a pointer into input, initially pointing at the start of the string.+ // 3. Let seen cue be false.++ // 4. If input is less than six characters long, then abort these steps. The file does not start with the+ // correct WebVTT file signature and was therefore not successfully processed.+ if self.input.len() < 6 {+ return None;+ }++ // 5. If input is exactly six characters long but does not exactly equal "WEBVTT", then abort these steps. The+ // file does not start with the correct WebVTT file signature and was therefore not successfully processed.+ // 6. If input is more than six characters long but the first six characters do not exactly equal "WEBVTT", or+ // the seventh character is not a U+0020 SPACE character, a U+0009 CHARACTER TABULATION (tab) character, or a+ // U+000A LINE FEED (LF) character, then abort these steps. The file does not start with the correct WebVTT+ // file signature and was therefore not successfully processed.+ if !self.input.starts_with(&utf16("WEBVTT")) {+ return None;+ }+ if self.input.len() > 6 && !matches!(self.input[6], 0x20 | 0x09 | LINE_FEED) {+ return None;+ }++ // 7. Collect a sequence of code points that are not U+000A LINE FEED (LF) characters.+ self.collect_a_sequence_of_code_points_that_are_not_line_feeds();++ // 8. If position is past the end of input, then abort these steps. The file was successfully processed, but it+ // contains no useful data and so no WebVTT cues were added to output.+ if self.lexer.is_eof() {+ return Some(output);+ }++ // 9. The character indicated by position is a U+000A LINE FEED (LF) character. Advance position to the next+ // character in input.+ self.lexer.ignore(1);++ // 10. If position is past the end of input, then abort these steps. The file was successfully processed, but it+ // contains no useful data and so no WebVTT cues were added to output.+ if self.lexer.is_eof() {+ return Some(output);+ }++ // 11. Header: If the character indicated by position is not a U+000A LINE FEED (LF) character, then collect a+ // WebVTT block with the in header flag set. Otherwise, advance position to the next character in input.+ if self.lexer.peek() == Some(LINE_FEED) {+ self.lexer.ignore(1);+ } else {+ self.collect_a_webvtt_block(true);+ }++ // 12. Collect a sequence of code points that are U+000A LINE FEED (LF) characters.+ self.collect_a_sequence_of_line_feeds();++ // FIXME: 13. Let regions be an empty text track list of regions.++ // 14. Block loop: While position doesn't point past the end of input:+ while !self.lexer.is_eof() {+ // 1. Collect a WebVTT block, and let block be the returned value.+ let block = self.collect_a_webvtt_block(false);++ // 2. If block is a WebVTT cue, add block to the text track list of cues output.+ if let Some(block) = block {+ output.push(block);+ }++ // FIXME: 3. Otherwise, if block is a CSS style sheet, add block to stylesheets.+ // FIXME: 4. Otherwise, if block is a WebVTT region object, add block to regions.++ // 5. Collect a sequence of code points that are U+000A LINE FEED (LF) characters.+ self.collect_a_sequence_of_line_feeds();+ }++ // 15. End: The file has ended. Abort these steps. The WebVTT parser has finished. The file was successfully+ // processed.+ Some(output)+ }+}++/// https://w3c.github.io/webvtt/#webvtt-parser+///+/// Returns None if the file does not start with the WebVTT file signature.+pub(crate) fn parse_webvtt_file(bytes: &[u8]) -> Option<Vec<ParsedCue>> {+ // A WebVTT parser, given an input byte stream, a text track list of cues output, and a collection of CSS style+ // sheets stylesheets, must decode the byte stream using the UTF-8 decode algorithm, and then must parse the+ // resulting string according to the WebVTT parser algorithm below.+ let decoded = String::from_utf8_lossy(bytes);+ let decoded = decoded.strip_prefix('\u{FEFF}').unwrap_or(&decoded);++ // 1. Let input be the string being parsed, after conversion to Unicode, and with the following transformations+ // applied:+ // - Replace all U+0000 NULL characters by U+FFFD REPLACEMENT CHARACTERs.+ // - Replace each U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pair by a single U+000A LINE FEED+ // (LF) character.+ // - Replace all remaining U+000D CARRIAGE RETURN characters by U+000A LINE FEED (LF) characters.+ let mut input = Vec::with_capacity(decoded.len());+ let mut code_units = decoded.encode_utf16().peekable();+ while let Some(code_unit) = code_units.next() {+ match code_unit {+ 0 => input.push(REPLACEMENT_CHARACTER),+ CARRIAGE_RETURN => {+ code_units.next_if_eq(&LINE_FEED);+ input.push(LINE_FEED);+ }+ _ => input.push(code_unit),+ }+ }++ Parser::new(&input).parse()+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_vtt/vtt_cue.rs b/Libraries/LibWeb/Bindings/Rust/src/web_vtt/vtt_cue.rsnew file mode 100644index 00000000000..8d71bc25148--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/web_vtt/vtt_cue.rs@@ -0,0 +1,328 @@+/*+ * Copyright (c) 2024-2025, Jamie Mansfield <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! VTTCue, https://w3c.github.io/webvtt/#vttcue++use core::cell::{Cell, RefCell};+use core::ffi::c_void;+use core::ptr::NonNull;++use ak::Utf16String;+use libjs_rust::api::{Trace, Vm};++use crate::bindings::event_target::{CppEventTarget, GetTheParent};+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::html::text_track_cue::TextTrackCue;+use crate::web_vtt::vtt_region::VTTRegion;++/// The enumeration AutoKeyword of WebVTT/VTTCue.idl.+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum AutoKeyword {+ Auto,+}++/// The union LineAndPositionSetting of WebVTT/VTTCue.idl, whose members the bindings convert.+#[derive(Clone, Copy, PartialEq)]+pub(crate) enum LineAndPositionSetting {+ Double(f64),+ AutoKeyword(AutoKeyword),+}++/// The enumeration DirectionSetting of WebVTT/VTTCue.idl.+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum DirectionSetting {+ Empty,+ Rl,+ Lr,+}++/// The enumeration LineAlignSetting of WebVTT/VTTCue.idl.+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum LineAlignSetting {+ Start,+ Center,+ End,+}++/// The enumeration PositionAlignSetting of WebVTT/VTTCue.idl.+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum PositionAlignSetting {+ LineLeft,+ Center,+ LineRight,+ Auto,+}++/// The enumeration AlignSetting of WebVTT/VTTCue.idl.+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum AlignSetting {+ Start,+ Center,+ End,+ Left,+ Right,+}++#[derive(Clone, Copy, PartialEq, Eq)]+enum WritingDirection {+ // https://w3c.github.io/webvtt/#webvtt-cue-horizontal-writing-direction+ Horizontal,++ // https://w3c.github.io/webvtt/#webvtt-cue-vertical-growing-left-writing-direction+ VerticalGrowingLeft,++ // https://w3c.github.io/webvtt/#webvtt-cue-vertical-growing-right-writing-direction+ VerticalGrowingRight,+}++// https://w3c.github.io/webvtt/#vttcue+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct VTTCue {+ cue: TextTrackCue,++ // https://w3c.github.io/webvtt/#cue-text+ #[gc(untraced)]+ text: RefCell<Utf16String>,++ // https://w3c.github.io/webvtt/#webvtt-cue-writing-direction+ #[gc(untraced)]+ writing_direction: Cell<WritingDirection>,++ // https://w3c.github.io/webvtt/#webvtt-cue-snap-to-lines-flag+ snap_to_lines: Cell<bool>,++ // https://w3c.github.io/webvtt/#webvtt-cue-line+ #[gc(untraced)]+ line: Cell<LineAndPositionSetting>,++ // https://w3c.github.io/webvtt/#webvtt-cue-line-alignment+ #[gc(untraced)]+ line_alignment: Cell<LineAlignSetting>,++ // https://w3c.github.io/webvtt/#webvtt-cue-position+ #[gc(untraced)]+ position: Cell<LineAndPositionSetting>,++ // https://w3c.github.io/webvtt/#webvtt-cue-position-alignment+ #[gc(untraced)]+ position_alignment: Cell<PositionAlignSetting>,++ // https://w3c.github.io/webvtt/#webvtt-cue-size+ size: Cell<f64>,++ // https://w3c.github.io/webvtt/#webvtt-cue-text-alignment+ #[gc(untraced)]+ text_alignment: Cell<AlignSetting>,++ // https://w3c.github.io/webvtt/#webvtt-cue-region+ region: Cell<Option<Ref<VTTRegion>>>,+}++impl Inherits<TextTrackCue> for VTTCue {+ fn parent(&self) -> &TextTrackCue {+ &self.cue+ }+}++impl Wrappable for VTTCue {+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {+ self.cue.cpp_parent()+ }+}++impl GetTheParent for VTTCue {+ fn get_the_parent(&self) -> Option<CppEventTarget> {+ self.cue.get_the_parent()+ }+}++impl VTTCue {+ // https://w3c.github.io/webvtt/#dom-vttcue-vttcue+ pub(crate) fn create(vm: &Vm, start_time: f64, end_time: f64, text: Utf16String) -> WebIdlResult<Ref<VTTCue>> {+ // 1. Create a new WebVTT cue. Let cue be that WebVTT cue.+ // 2. Let cue’s text track cue start time be the value of the startTime argument.+ // 3. If the value of the endTime argument is negative Infinity or a Not-a-Number (NaN) value, then throw a+ // TypeError exception. Otherwise, let cue’s text track cue end time be the value of the endTime argument.+ // NB: The cue is allocated below, once nothing can throw.+ if end_time == f64::NEG_INFINITY || end_time.is_nan() {+ return Err(Exception::type_error("End time is negative infinity or NaN"));+ }++ let cue = allocate(vm, |_| VTTCue {+ // 4. Let cue’s cue text be the value of the text argument, and let the rules for extracting the chapter+ // title be the WebVTT rules for extracting the chapter title.+ // FIXME: let the rules for extracting the chapter title be the WebVTT rules for extracting the chapter+ // title.+ text: RefCell::new(text),++ // 5. Let cue’s text track cue identifier be the empty string.+ // 6. Let cue’s text track cue pause-on-exit flag be false.+ cue: TextTrackCue::new(start_time, end_time),++ // 7. Let cue’s WebVTT cue region be null.+ region: Cell::new(None),++ // 8. Let cue’s WebVTT cue writing direction be horizontal.+ writing_direction: Cell::new(WritingDirection::Horizontal),++ // 9. Let cue’s WebVTT cue snap-to-lines flag be true.+ snap_to_lines: Cell::new(true),++ // 10. Let cue’s WebVTT cue line be auto.+ line: Cell::new(LineAndPositionSetting::AutoKeyword(AutoKeyword::Auto)),++ // 11. Let cue’s WebVTT cue line alignment be start alignment.+ line_alignment: Cell::new(LineAlignSetting::Start),++ // 12. Let cue’s WebVTT cue position be auto.+ position: Cell::new(LineAndPositionSetting::AutoKeyword(AutoKeyword::Auto)),++ // 13. Let cue’s WebVTT cue position alignment be auto.+ position_alignment: Cell::new(PositionAlignSetting::Auto),++ // 14. Let cue’s WebVTT cue size be 100.+ size: Cell::new(100.0),++ // 15. Let cue’s WebVTT cue text alignment be center alignment.+ text_alignment: Cell::new(AlignSetting::Center),+ });+ cue.cue.event_target().set_owner(cue);++ // 16. Return the VTTCue object representing cue.+ Ok(cue)+ }++ // https://w3c.github.io/webvtt/#dom-vttcue-vttcue+ pub(crate) fn construct(+ cx: &mut CallContext,+ start_time: f64,+ end_time: f64,+ text: Utf16String,+ ) -> WebIdlResult<Ref<VTTCue>> {+ Self::create(cx.vm(), start_time, end_time, text)+ }++ // https://w3c.github.io/webvtt/#dom-vttcue-region+ pub(crate) fn region(&self, _: &mut CallContext) -> WebIdlResult<Option<Ref<VTTRegion>>> {+ Ok(self.region.get())+ }++ // https://w3c.github.io/webvtt/#dom-vttcue-region+ pub(crate) fn set_region(&self, _: &mut CallContext, value: Option<Ref<VTTRegion>>) -> WebIdlResult<()> {+ self.region.set(value);+ Ok(())+ }++ // https://w3c.github.io/webvtt/#dom-vttcue-vertical+ pub(crate) fn vertical(&self, _: &mut CallContext) -> WebIdlResult<DirectionSetting> {+ Ok(match self.writing_direction.get() {+ WritingDirection::Horizontal => DirectionSetting::Empty,+ WritingDirection::VerticalGrowingLeft => DirectionSetting::Rl,+ WritingDirection::VerticalGrowingRight => DirectionSetting::Lr,+ })+ }++ // https://w3c.github.io/webvtt/#dom-vttcue-vertical+ pub(crate) fn set_vertical(&self, _: &mut CallContext, value: DirectionSetting) -> WebIdlResult<()> {+ self.writing_direction.set(match value {+ DirectionSetting::Empty => WritingDirection::Horizontal,+ DirectionSetting::Rl => WritingDirection::VerticalGrowingLeft,+ DirectionSetting::Lr => WritingDirection::VerticalGrowingRight,+ });+ Ok(())+ }++ // https://w3c.github.io/webvtt/#dom-vttcue-snaptolines+ pub(crate) fn snap_to_lines(&self, _: &mut CallContext) -> WebIdlResult<bool> {+ Ok(self.snap_to_lines.get())+ }++ // https://w3c.github.io/webvtt/#dom-vttcue-snaptolines+ pub(crate) fn set_snap_to_lines(&self, _: &mut CallContext, value: bool) -> WebIdlResult<()> {+ self.snap_to_lines.set(value);+ Ok(())+ }++ // https://w3c.github.io/webvtt/#dom-vttcue-line+ pub(crate) fn line(&self, _: &mut CallContext) -> WebIdlResult<LineAndPositionSetting> {+ Ok(self.line.get())+ }++ // https://w3c.github.io/webvtt/#dom-vttcue-line+ pub(crate) fn set_line(&self, _: &mut CallContext, value: LineAndPositionSetting) -> WebIdlResult<()> {+ self.line.set(value);+ Ok(())+ }++ // https://w3c.github.io/webvtt/#dom-vttcue-linealign+ pub(crate) fn line_align(&self, _: &mut CallContext) -> WebIdlResult<LineAlignSetting> {+ Ok(self.line_alignment.get())+ }++ // https://w3c.github.io/webvtt/#dom-vttcue-linealign+ pub(crate) fn set_line_align(&self, _: &mut CallContext, value: LineAlignSetting) -> WebIdlResult<()> {+ self.line_alignment.set(value);+ Ok(())+ }++ // https://w3c.github.io/webvtt/#dom-vttcue-position+ pub(crate) fn position(&self, _: &mut CallContext) -> WebIdlResult<LineAndPositionSetting> {+ Ok(self.position.get())+ }++ // https://w3c.github.io/webvtt/#dom-vttcue-position+ pub(crate) fn set_position(&self, _: &mut CallContext, value: LineAndPositionSetting) -> WebIdlResult<()> {+ self.position.set(value);+ Ok(())+ }++ // https://w3c.github.io/webvtt/#dom-vttcue-positionalign+ pub(crate) fn position_align(&self, _: &mut CallContext) -> WebIdlResult<PositionAlignSetting> {+ Ok(self.position_alignment.get())+ }++ // https://w3c.github.io/webvtt/#dom-vttcue-positionalign+ pub(crate) fn set_position_align(&self, _: &mut CallContext, value: PositionAlignSetting) -> WebIdlResult<()> {+ self.position_alignment.set(value);+ Ok(())+ }++ // https://w3c.github.io/webvtt/#dom-vttcue-size+ pub(crate) fn size(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.size.get())+ }++ // https://w3c.github.io/webvtt/#dom-vttcue-size+ pub(crate) fn set_size(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ self.size.set(value);+ Ok(())+ }++ // https://w3c.github.io/webvtt/#dom-vttcue-align+ pub(crate) fn align(&self, _: &mut CallContext) -> WebIdlResult<AlignSetting> {+ Ok(self.text_alignment.get())+ }++ // https://w3c.github.io/webvtt/#dom-vttcue-align+ pub(crate) fn set_align(&self, _: &mut CallContext, value: AlignSetting) -> WebIdlResult<()> {+ self.text_alignment.set(value);+ Ok(())+ }++ // https://w3c.github.io/webvtt/#dom-vttcue-text+ pub(crate) fn text(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {+ Ok(self.text.borrow().clone())+ }++ // https://w3c.github.io/webvtt/#dom-vttcue-text+ pub(crate) fn set_text(&self, _: &mut CallContext, value: Utf16String) -> WebIdlResult<()> {+ *self.text.borrow_mut() = value;+ Ok(())+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_vtt/vtt_region.rs b/Libraries/LibWeb/Bindings/Rust/src/web_vtt/vtt_region.rsnew file mode 100644index 00000000000..301b92cd0b0--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/web_vtt/vtt_region.rs@@ -0,0 +1,215 @@+/*+ * Copyright (c) 2024, Jamie Mansfield <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! VTTRegion, https://w3c.github.io/webvtt/#vttregion++use core::cell::{Cell, RefCell};++use ak::Utf16String;+use libjs_rust::api::Trace;++use crate::bindings::interface::Wrappable;+use crate::bindings::{CallContext, Exception, WebIdlResult};++/// The enumeration ScrollSetting of WebVTT/VTTRegion.idl.+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum ScrollSetting {+ Empty,+ Up,+}++// https://w3c.github.io/webvtt/#vttregion+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct VTTRegion {+ // https://w3c.github.io/webvtt/#webvtt-region-identifier+ #[gc(untraced)]+ identifier: RefCell<Utf16String>,++ // https://w3c.github.io/webvtt/#webvtt-region-width+ width: Cell<f64>,++ // https://w3c.github.io/webvtt/#webvtt-region-lines+ lines: Cell<u32>,++ // https://w3c.github.io/webvtt/#webvtt-region-anchor+ anchor_x: Cell<f64>,+ anchor_y: Cell<f64>,++ // https://w3c.github.io/webvtt/#webvtt-region-viewport-anchor+ viewport_anchor_x: Cell<f64>,+ viewport_anchor_y: Cell<f64>,++ // https://w3c.github.io/webvtt/#webvtt-region-scroll+ #[gc(untraced)]+ scroll_setting: Cell<ScrollSetting>,+}++impl Wrappable for VTTRegion {}++impl VTTRegion {+ // https://w3c.github.io/webvtt/#dom-vttregion-vttregion+ pub(crate) fn construct(_: &mut CallContext) -> WebIdlResult<Self> {+ // 1. Create a new WebVTT region. Let region be that WebVTT region.+ let region = Self {+ // 2. Let region’s WebVTT region identifier be the empty string.+ identifier: RefCell::new(Utf16String::from_utf8("")),++ // 3. Let region’s WebVTT region width be 100.+ width: Cell::new(100.0),++ // 4. Let region’s WebVTT region lines be 3.+ lines: Cell::new(3),++ // 5. Let region’s text track region regionAnchorX be 0.+ anchor_x: Cell::new(0.0),++ // 6. Let region’s text track region regionAnchorY be 100.+ anchor_y: Cell::new(100.0),++ // 7. Let region’s text track region viewportAnchorX be 0.+ viewport_anchor_x: Cell::new(0.0),++ // 8. Let region’s text track region viewportAnchorY be 100.+ viewport_anchor_y: Cell::new(100.0),++ // 9. Let region’s WebVTT region scroll be the empty string.+ scroll_setting: Cell::new(ScrollSetting::Empty),+ };++ // 10. Return the VTTRegion object representing region.+ Ok(region)+ }++ // https://w3c.github.io/webvtt/#dom-vttregion-id+ pub(crate) fn id(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {+ Ok(self.identifier.borrow().clone())+ }++ // https://w3c.github.io/webvtt/#dom-vttregion-id+ pub(crate) fn set_id(&self, _: &mut CallContext, value: Utf16String) -> WebIdlResult<()> {+ *self.identifier.borrow_mut() = value;+ Ok(())+ }++ // https://w3c.github.io/webvtt/#dom-vttregion-width+ pub(crate) fn width(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.width.get())+ }++ // https://w3c.github.io/webvtt/#dom-vttregion-width+ pub(crate) fn set_width(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // On setting, if the new value is negative or greater than 100, then an IndexSizeError exception must be thrown.+ if !(0.0..=100.0).contains(&value) {+ return Err(Exception::index_size_error(Utf16String::from_utf8(+ "Value is negative or greater than 100",+ )));+ }++ // Otherwise, the WebVTT region width must be set to the new value.+ self.width.set(value);+ Ok(())+ }++ // https://w3c.github.io/webvtt/#dom-vttregion-lines+ pub(crate) fn lines(&self, _: &mut CallContext) -> WebIdlResult<u32> {+ Ok(self.lines.get())+ }++ // https://w3c.github.io/webvtt/#dom-vttregion-lines+ pub(crate) fn set_lines(&self, _: &mut CallContext, value: u32) -> WebIdlResult<()> {+ self.lines.set(value);+ Ok(())+ }++ // https://w3c.github.io/webvtt/#dom-vttregion-regionanchorx+ pub(crate) fn region_anchor_x(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.anchor_x.get())+ }++ // https://w3c.github.io/webvtt/#dom-vttregion-regionanchorx+ pub(crate) fn set_region_anchor_x(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // On setting, if the new value is negative or greater than 100, then an IndexSizeError exception must be thrown.+ if !(0.0..=100.0).contains(&value) {+ return Err(Exception::index_size_error(Utf16String::from_utf8(+ "Value is negative or greater than 100",+ )));+ }++ // Otherwise, the WebVTT region anchor X distance must be set to the new value.+ self.anchor_x.set(value);+ Ok(())+ }++ // https://w3c.github.io/webvtt/#dom-vttregion-regionanchory+ pub(crate) fn region_anchor_y(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.anchor_y.get())+ }++ // https://w3c.github.io/webvtt/#dom-vttregion-regionanchory+ pub(crate) fn set_region_anchor_y(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // On setting, if the new value is negative or greater than 100, then an IndexSizeError exception must be thrown.+ if !(0.0..=100.0).contains(&value) {+ return Err(Exception::index_size_error(Utf16String::from_utf8(+ "Value is negative or greater than 100",+ )));+ }++ // Otherwise, the WebVTT region anchor Y distance must be set to the new value.+ self.anchor_y.set(value);+ Ok(())+ }++ // https://w3c.github.io/webvtt/#dom-vttregion-viewportanchorx+ pub(crate) fn viewport_anchor_x(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.viewport_anchor_x.get())+ }++ // https://w3c.github.io/webvtt/#dom-vttregion-viewportanchorx+ pub(crate) fn set_viewport_anchor_x(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // On setting, if the new value is negative or greater than 100, then an IndexSizeError exception must be thrown.+ if !(0.0..=100.0).contains(&value) {+ return Err(Exception::index_size_error(Utf16String::from_utf8(+ "Value is negative or greater than 100",+ )));+ }++ // Otherwise, the WebVTT region viewport anchor X distance must be set to the new value.+ self.viewport_anchor_x.set(value);+ Ok(())+ }++ // https://w3c.github.io/webvtt/#dom-vttregion-viewportanchory+ pub(crate) fn viewport_anchor_y(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.viewport_anchor_y.get())+ }++ // https://w3c.github.io/webvtt/#dom-vttregion-viewportanchory+ pub(crate) fn set_viewport_anchor_y(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // On setting, if the new value is negative or greater than 100, then an IndexSizeError exception must be thrown.+ if !(0.0..=100.0).contains(&value) {+ return Err(Exception::index_size_error(Utf16String::from_utf8(+ "Value is negative or greater than 100",+ )));+ }++ // Otherwise, the WebVTT region viewport anchor Y distance must be set to the new value.+ self.viewport_anchor_y.set(value);+ Ok(())+ }++ // https://w3c.github.io/webvtt/#dom-vttregion-scroll+ pub(crate) fn scroll(&self, _: &mut CallContext) -> WebIdlResult<ScrollSetting> {+ Ok(self.scroll_setting.get())+ }++ // https://w3c.github.io/webvtt/#dom-vttregion-scroll+ pub(crate) fn set_scroll(&self, _: &mut CallContext, value: ScrollSetting) -> WebIdlResult<()> {+ self.scroll_setting.set(value);+ Ok(())+ }+}diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex 6fc1b83f0f4..26330129d94 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -950,7 +950,6 @@ set(SOURCESWebSockets/WebSocket.cppWebVTT/Parser.cppWebVTT/VTTCue.cpp- WebVTT/VTTRegion.cppXHR/FormData.cppXHR/XMLHttpRequest.cppXLink/AttributeNames.cppdiff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.hindex 4a0fc1560e1..7c54724a520 100644--- a/Libraries/LibWeb/Forward.h+++ b/Libraries/LibWeb/Forward.h@@ -1266,7 +1266,6 @@ class WebSocket;namespace Web::WebVTT {class VTTCue;-class VTTRegion;}diff --git a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp b/Libraries/LibWeb/HTML/HTMLMediaElement.cppindex d659ef10c24..15448ed093c 100644--- a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLMediaElement.cpp@@ -4115,7 +4115,7 @@ void HTMLMediaElement::time_marches_on(TimeMarchesOnReason reason)// 14. Queue a media element task given the media element for each task in events, in list order.for (auto& event : events) {queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(move(event.name), event.target), [](auto& name, auto& target, HTMLMediaElement& self) {- target->dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), name));+ target->event_target()->dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), name));}));}diff --git a/Libraries/LibWeb/HTML/HTMLTrackElement.cpp b/Libraries/LibWeb/HTML/HTMLTrackElement.cppindex 9b862d85988..2bcfd762afb 100644--- a/Libraries/LibWeb/HTML/HTMLTrackElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLTrackElement.cpp@@ -302,7 +302,7 @@ void HTMLTrackElement::start_the_track_processing_model_parallel_steps()self.queue_an_element_task(Task::Source::Networking, GC::create_function(GC::Heap::the(), GC::captures(self, cues.release_value(), src_generation), [](auto& self, auto& cues, auto& src_generation) {if (src_generation == self.m_src_generation) {for (auto const& parsed_cue : cues) {- auto cue = MUST(WebVTT::VTTCue::create(parsed_cue.start_time, parsed_cue.end_time, parsed_cue.text));+ auto cue = WebVTT::VTTCue::create(parsed_cue.start_time, parsed_cue.end_time, parsed_cue.text);cue->set_id(parsed_cue.identifier);self.m_track->add_cue(cue);}diff --git a/Libraries/LibWeb/HTML/TextTrackCue.cpp b/Libraries/LibWeb/HTML/TextTrackCue.cppindex 2094d8645ff..b040e6af690 100644--- a/Libraries/LibWeb/HTML/TextTrackCue.cpp+++ b/Libraries/LibWeb/HTML/TextTrackCue.cpp@@ -4,92 +4,118 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/Math.h>-#include <LibWeb/HTML/EventNames.h>+#include <LibWeb/DOM/EventTarget.h>#include <LibWeb/HTML/HTMLMediaElement.h>+#include <LibWeb/HTML/TextTrack.h>#include <LibWeb/HTML/TextTrackCue.h>namespace Web::HTML {-GC_DEFINE_ALLOCATOR(TextTrackCue);+extern "C" {++// Defined in Bindings/Rust/src/html/exports.rs.+void* web_text_track_cue_event_target(void* cue);+void* web_text_track_cue_track(void* cue);+void web_text_track_cue_set_track(void* cue, void* track);+FlatPtr web_text_track_cue_id(void* cue);+void web_text_track_cue_set_id(void* cue, FlatPtr id);+double web_text_track_cue_start_time(void* cue);+double web_text_track_cue_end_time(void* cue);+bool web_text_track_cue_pause_on_exit(void* cue);+bool web_text_track_cue_is_active(void* cue);+void web_text_track_cue_set_active(void* cue, bool active);+u64 web_text_track_cue_order_added(void* cue);+void web_text_track_cue_set_order_added(void* cue, u64 order_added);++// Declared in Bindings/Rust/src/html/text_track_cue.rs.+void web_html_text_track_cue_timing_changed(void* track);+}-TextTrackCue::TextTrackCue(GC::Ptr<TextTrack> track)- : DOM::EventTarget()- , m_track(track)+static void* to_abi(TextTrackCue const* cue){+ return const_cast<TextTrackCue*>(cue);}-TextTrackCue::~TextTrackCue() = default;--void TextTrackCue::visit_edges(JS::Cell::Visitor& visitor)+static TextTrack& track_from_abi(void* track){- Base::visit_edges(visitor);- visitor.visit(m_track);+ return *static_cast<TextTrack*>(static_cast<GC::Cell*>(track));}-void TextTrackCue::run_time_marches_on_if_needed()+// https://html.spec.whatwg.org/multipage/media.html#dom-texttrackcue-starttime+// https://html.spec.whatwg.org/multipage/media.html#dom-texttrackcue-endtime+void web_html_text_track_cue_timing_changed(void* track){- if (!m_track)- return;- if (auto media_element = m_track->media_element(); media_element && !media_element->show_poster())+ auto& text_track = track_from_abi(track);+ text_track.sort_text_track_list_of_cues();++ // ...if the TextTrackCue object's text track cue is in a text track's list of cues, and that text track is in a media+ // element's list of text tracks, and the media element's show poster flag is not set, then run the time marches on+ // steps for that media element.+ if (auto media_element = text_track.media_element(); media_element && !media_element->show_poster())media_element->time_marches_on(HTMLMediaElement::TimeMarchesOnReason::Other);}-// https://html.spec.whatwg.org/multipage/media.html#dom-texttrackcue-starttime-void TextTrackCue::set_start_time(double start_time)+GC::Ref<DOM::EventTarget> TextTrackCue::event_target() const{- // On setting, the text track cue start time must be set to the new value, interpreted in seconds;- m_start_time = start_time;- if (m_track)- m_track->sort_text_track_list_of_cues();+ return *static_cast<DOM::EventTarget*>(static_cast<GC::Cell*>(web_text_track_cue_event_target(to_abi(this))));+}- // then, if the TextTrackCue object's text track cue is in a text track's list of cues, and that text track is in a media- // element's list of text tracks, and the media element's show poster flag is not set, then run the time marches on steps- // for that media element.- run_time_marches_on_if_needed();+GC::Ptr<TextTrack> TextTrackCue::track() const+{+ auto* track = web_text_track_cue_track(to_abi(this));+ if (!track)+ return nullptr;+ return track_from_abi(track);}-// https://html.spec.whatwg.org/multipage/media.html#dom-texttrackcue-endtime-WebIDL::ExceptionOr<void> TextTrackCue::set_end_time(double end_time)+void TextTrackCue::set_track(GC::Ptr<TextTrack> track)+{+ web_text_track_cue_set_track(to_abi(this), track ? static_cast<GC::Cell*>(track.ptr()) : nullptr);+}++Utf16String TextTrackCue::id() const{- // On setting, if the new value is negative Infinity or a Not-a-Number (NaN) value, then throw a TypeError exception.- if (end_time == -AK::Infinity<double> || isnan(end_time))- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Value is negative infinity or NaN"_utf16 };+ return Utf16String::adopt_raw(web_text_track_cue_id(to_abi(this)));+}- // Otherwise, the text track cue end time must be set to the new value.- m_end_time = end_time;- if (m_track)- m_track->sort_text_track_list_of_cues();+void TextTrackCue::set_id(Utf16String const& id)+{+ web_text_track_cue_set_id(to_abi(this), id.raw_identity());+}- // Then, if the TextTrackCue object's text track cue is in a text track's list of cues, and that text track is in a media- // element's list of text tracks, and the media element's show poster flag is not set, then run the time marches on steps- // for that media element.- run_time_marches_on_if_needed();- return {};+double TextTrackCue::start_time() const+{+ return web_text_track_cue_start_time(to_abi(this));+}++double TextTrackCue::end_time() const+{+ return web_text_track_cue_end_time(to_abi(this));+}++bool TextTrackCue::pause_on_exit() const+{+ return web_text_track_cue_pause_on_exit(to_abi(this));}-// https://html.spec.whatwg.org/multipage/media.html#handler-texttrackcue-onenter-WebIDL::CallbackType* TextTrackCue::onenter()+bool TextTrackCue::is_active() const{- return event_handler_attribute(HTML::EventNames::enter);+ return web_text_track_cue_is_active(to_abi(this));}-// https://html.spec.whatwg.org/multipage/media.html#handler-texttrackcue-onenter-void TextTrackCue::set_onenter(WebIDL::CallbackType* event_handler)+void TextTrackCue::set_active(bool active){- set_event_handler_attribute(HTML::EventNames::enter, event_handler);+ web_text_track_cue_set_active(to_abi(this), active);}-// https://html.spec.whatwg.org/multipage/media.html#handler-texttrackcue-onexit-WebIDL::CallbackType* TextTrackCue::onexit()+u64 TextTrackCue::order_added() const{- return event_handler_attribute(HTML::EventNames::exit);+ return web_text_track_cue_order_added(to_abi(this));}-// https://html.spec.whatwg.org/multipage/media.html#handler-texttrackcue-onexit-void TextTrackCue::set_onexit(WebIDL::CallbackType* event_handler)+void TextTrackCue::set_order_added(u64 order_added){- set_event_handler_attribute(HTML::EventNames::exit, event_handler);+ web_text_track_cue_set_order_added(to_abi(this), order_added);}}diff --git a/Libraries/LibWeb/HTML/TextTrackCue.h b/Libraries/LibWeb/HTML/TextTrackCue.hindex fbaa52fc928..0e56887cc8e 100644--- a/Libraries/LibWeb/HTML/TextTrackCue.h+++ b/Libraries/LibWeb/HTML/TextTrackCue.h@@ -7,73 +7,35 @@#pragma once#include <AK/Utf16String.h>-#include <AK/Utf16View.h>-#include <LibGC/RootVector.h>-#include <LibWeb/DOM/EventTarget.h>-#include <LibWeb/HTML/TextTrack.h>+#include <LibGC/Ptr.h>+#include <LibWeb/Bindings/RustInterface.h>+#include <LibWeb/Bindings/TextTrackCue.h>+#include <LibWeb/Forward.h>namespace Web::HTML {// https://html.spec.whatwg.org/multipage/media.html#texttrackcue-class TextTrackCue : public DOM::EventTarget {- WEB_WRAPPABLE(TextTrackCue, DOM::EventTarget);- GC_DECLARE_ALLOCATOR(TextTrackCue);+class TextTrackCue : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(TextTrackCue, text_track_cue)public:- virtual ~TextTrackCue() override;+ GC::Ref<DOM::EventTarget> event_target() const;- GC::Ptr<TextTrack> track() const { return m_track; }- void set_track(GC::Ptr<TextTrack> track) { m_track = track; }- static constexpr size_t track_offset() { return offsetof(TextTrackCue, m_track); }+ GC::Ptr<TextTrack> track() const;+ void set_track(GC::Ptr<TextTrack>);- Utf16String const& id() const { return m_identifier; }- void set_id(Utf16View id) { m_identifier = Utf16String::from_utf16(id); }+ Utf16String id() const;+ void set_id(Utf16String const&);- double start_time() const { return m_start_time; }- void set_start_time(double start_time);+ double start_time() const;+ double end_time() const;+ bool pause_on_exit() const;- double end_time() const { return m_end_time; }- WebIDL::ExceptionOr<void> set_end_time(double end_time);+ bool is_active() const;+ void set_active(bool);- bool pause_on_exit() const { return m_pause_on_exit; }- void set_pause_on_exit(bool pause_on_exit) { m_pause_on_exit = pause_on_exit; }-- WebIDL::CallbackType* onenter();- void set_onenter(WebIDL::CallbackType*);-- WebIDL::CallbackType* onexit();- void set_onexit(WebIDL::CallbackType*);-- bool is_active() const { return m_active; }- void set_active(bool active) { m_active = active; }-- u64 order_added() const { return m_order_added; }- void set_order_added(u64 order_added) { m_order_added = order_added; }--protected:- TextTrackCue(GC::Ptr<TextTrack>);-- void run_time_marches_on_if_needed();- virtual void visit_edges(Visitor&) override;-- GC::Ptr<TextTrack> m_track;-- // https://html.spec.whatwg.org/multipage/media.html#text-track-cue-identifier- Utf16String m_identifier;-- // https://html.spec.whatwg.org/multipage/media.html#text-track-cue-start-time- double m_start_time;-- // https://html.spec.whatwg.org/multipage/media.html#text-track-cue-end-time- double m_end_time;-- // https://html.spec.whatwg.org/multipage/media.html#text-track-cue-pause-on-exit-flag- bool m_pause_on_exit;-- // https://html.spec.whatwg.org/multipage/media.html#text-track-cue-active-flag- bool m_active { false };-- u64 m_order_added { 0 };+ u64 order_added() const;+ void set_order_added(u64);};}diff --git a/Libraries/LibWeb/HTML/TextTrackCue.idl b/Libraries/LibWeb/HTML/TextTrackCue.idlindex 2c70b373eb2..07375be3714 100644--- a/Libraries/LibWeb/HTML/TextTrackCue.idl+++ b/Libraries/LibWeb/HTML/TextTrackCue.idl@@ -1,7 +1,7 @@// https://html.spec.whatwg.org/multipage/media.html#texttrackcue-[Exposed=Window]+[Exposed=Window, ImplementedIn=Rust]interface TextTrackCue : EventTarget {- [DirectGetter] readonly attribute TextTrack? track;+ readonly attribute TextTrack? track;attribute DOMString id;attribute double startTime;diff --git a/Libraries/LibWeb/WebVTT/Parser.cpp b/Libraries/LibWeb/WebVTT/Parser.cppindex 3141230b9a4..0c52cb9e183 100644--- a/Libraries/LibWeb/WebVTT/Parser.cpp+++ b/Libraries/LibWeb/WebVTT/Parser.cpp@@ -4,495 +4,31 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/CharacterTypes.h>-#include <AK/GenericShorthands.h>-#include <AK/Utf16StringBuilder.h>#include <LibWeb/WebVTT/Parser.h>-#include <LibWebCommon/Infra/CharacterTypes.h>namespace Web::WebVTT {-namespace {--class Parser {-public:- explicit Parser(Utf16View input)- : m_input(input)- {- }-- Optional<Vector<ParsedCue>> parse();--private:- bool is_past_end() const { return m_position >= m_input.length_in_code_units(); }- char16_t current() const { return m_input.code_unit_at(m_position); }-- Utf16View collect_a_sequence_of_code_points_that_are_not_line_feeds();- void collect_a_sequence_of_line_feeds();- Optional<ParsedCue> collect_a_webvtt_block(bool in_header);-- Utf16View m_input;- size_t m_position { 0 };- bool m_seen_cue { false };-};--Utf16View Parser::collect_a_sequence_of_code_points_that_are_not_line_feeds()-{- auto start = m_position;- while (!is_past_end() && current() != '\n')- ++m_position;- return m_input.substring_view(start, m_position - start);-}--void Parser::collect_a_sequence_of_line_feeds()-{- while (!is_past_end() && current() == '\n')- ++m_position;-}--class StringScanner {-public:- explicit StringScanner(Utf16View input)- : m_input(input)- {- }-- bool is_past_end() const { return m_position >= m_input.length_in_code_units(); }- char16_t current() const { return m_input.code_unit_at(m_position); }- void advance() { ++m_position; }-- void skip_whitespace()- {- while (!is_past_end() && Infra::is_ascii_whitespace(current()))- ++m_position;- }-- Utf16View collect_ascii_digits()- {- auto start = m_position;- while (!is_past_end() && is_ascii_digit(current()))- ++m_position;- return m_input.substring_view(start, m_position - start);- }-- bool consume(char16_t code_unit)- {- if (is_past_end() || current() != code_unit)- return false;- ++m_position;- return true;- }--private:- Utf16View m_input;- size_t m_position { 0 };-};--u64 interpret_as_base_ten_integer(Utf16View digits)-{- u64 value = 0;- for (size_t i = 0; i < digits.length_in_code_units(); ++i)- value = (value * 10) + (digits.code_unit_at(i) - '0');- return value;-}--// https://w3c.github.io/webvtt/#collect-a-webvtt-timestamp-Optional<double> collect_a_webvtt_timestamp(StringScanner& scanner)-{- // 1. Let input and position be the same variables as those of the same name in the algorithm that invoked these- // steps.-- // 2. Let most significant units be minutes.- bool most_significant_units_are_hours = false;-- // 3. If position is past the end of input, return an error and abort these steps.- if (scanner.is_past_end())- return {};-- // 4. If the character indicated by position is not an ASCII digit, then return an error and abort these steps.- if (!is_ascii_digit(scanner.current()))- return {};-- // 5. Collect a sequence of code points that are ASCII digits, and let string be the collected substring.- auto string = scanner.collect_ascii_digits();-- // 6. Interpret string as a base-ten integer. Let value1 be that integer.- auto value1 = interpret_as_base_ten_integer(string);-- // 7. If string is not exactly two characters in length, or if value1 is greater than 59, let most significant units- // be hours.- if (string.length_in_code_units() != 2 || value1 > 59)- most_significant_units_are_hours = true;-- // 8. If position is beyond the end of input or if the character at position is not a U+003A COLON character (:),- // then return an error and abort these steps. Otherwise, move position forwards one character.- if (!scanner.consume(':'))- return {};-- // 9. Collect a sequence of code points that are ASCII digits, and let string be the collected substring.- string = scanner.collect_ascii_digits();-- // 10. If string is not exactly two characters in length, return an error and abort these steps.- if (string.length_in_code_units() != 2)- return {};-- // 11. Interpret string as a base-ten integer. Let value2 be that integer.- auto value2 = interpret_as_base_ten_integer(string);- u64 value3 = 0;-- // 12. If most significant units is hours, or if position is not beyond the end of input and the character at- // position is a U+003A COLON character (:), run these substeps:- if (most_significant_units_are_hours || (!scanner.is_past_end() && scanner.current() == ':')) {- // 1. If position is beyond the end of input or if the character at position is not a U+003A COLON character- // (:), then return an error and abort these steps. Otherwise, move position forwards one character.- if (!scanner.consume(':'))- return {};-- // 2. Collect a sequence of code points that are ASCII digits, and let string be the collected substring.- string = scanner.collect_ascii_digits();-- // 3. If string is not exactly two characters in length, return an error and abort these steps.- if (string.length_in_code_units() != 2)- return {};-- // 4. Interpret string as a base-ten integer. Let value3 be that integer.- value3 = interpret_as_base_ten_integer(string);- }- // Otherwise (if most significant units is not hours, and either position is beyond the end of input, or the- // character at position is not a U+003A COLON character (:)), let value3 have the value of value2, then value2 have- // the value of value1, then let value1 equal zero.- else {- value3 = value2;- value2 = value1;- value1 = 0;- }-- // 13. If position is beyond the end of input or if the character at position is not a U+002E FULL STOP character- // (.), then return an error and abort these steps. Otherwise, move position forwards one character.- if (!scanner.consume('.'))- return {};-- // 14. Collect a sequence of code points that are ASCII digits, and let string be the collected substring.- string = scanner.collect_ascii_digits();-- // 15. If string is not exactly three characters in length, return an error and abort these steps.- if (string.length_in_code_units() != 3)- return {};-- // 16. Interpret string as a base-ten integer. Let value4 be that integer.- auto value4 = interpret_as_base_ten_integer(string);-- // 17. If value2 is greater than 59 or if value3 is greater than 59, return an error and abort these steps.- if (value2 > 59 || value3 > 59)- return {};-- // 18. Let result be value1×60×60 + value2×60 + value3 + value4∕1000.- auto result = (static_cast<double>(value1) * 60 * 60) + (static_cast<double>(value2) * 60) + static_cast<double>(value3) + (static_cast<double>(value4) / 1000);-- // 19. Return result.- return result;-}--// https://w3c.github.io/webvtt/#collect-webvtt-cue-timings-and-settings-bool collect_webvtt_cue_timings_and_settings(Utf16View input, ParsedCue& cue)-{- // 1. Let input be the string being parsed.- // 2. Let position be a pointer into input, initially pointing at the start of the string.- StringScanner scanner { input };-- // 3. Skip whitespace.- scanner.skip_whitespace();-- // 4. Collect a WebVTT timestamp. If that algorithm fails, then abort these steps and return failure. Otherwise, let- // cue's text track cue start time be the collected time.- auto start_time = collect_a_webvtt_timestamp(scanner);- if (!start_time.has_value())- return false;- cue.start_time = *start_time;-- // 5. Skip whitespace.- scanner.skip_whitespace();-- // 6. If the character at position is not a U+002D HYPHEN-MINUS character (-) then abort these steps and return- // failure. Otherwise, move position forwards one character.- // 7. If the character at position is not a U+002D HYPHEN-MINUS character (-) then abort these steps and return- // failure. Otherwise, move position forwards one character.- // 8. If the character at position is not a U+003E GREATER-THAN SIGN character (>) then abort these steps and return- // failure. Otherwise, move position forwards one character.- if (!scanner.consume('-') || !scanner.consume('-') || !scanner.consume('>'))- return false;-- // 9. Skip whitespace.- scanner.skip_whitespace();-- // 10. Collect a WebVTT timestamp. If that algorithm fails, then abort these steps and return failure. Otherwise, let- // cue's text track cue end time be the collected time.- auto end_time = collect_a_webvtt_timestamp(scanner);- if (!end_time.has_value())- return false;- cue.end_time = *end_time;-- // FIXME: 11. Let remainder be the trailing substring of input starting at position.- // FIXME: 12. Parse the WebVTT cue settings from remainder using regions for cue.- return true;-}--bool is_block_keyword(Utf16View buffer, Utf16View keyword)-{- if (!buffer.starts_with(keyword))- return false;- auto remainder = buffer.substring_view(keyword.length_in_code_units());- for (size_t i = 0; i < remainder.length_in_code_units(); ++i) {- if (!Infra::is_ascii_whitespace(remainder.code_unit_at(i)))- return false;- }- return true;-}--// https://w3c.github.io/webvtt/#collect-a-webvtt-block-Optional<ParsedCue> Parser::collect_a_webvtt_block(bool in_header)-{- // 1. Let input, position, seen cue and regions be the same variables as those of the same name in the algorithm- // that invoked these steps.-- // 2. Let line count be zero.- size_t line_count = 0;-- // 3. Let previous position be position.- auto previous_position = m_position;-- // 4. Let line be the empty string.- Utf16View line;-- // 5. Let buffer be the empty string.- Utf16StringBuilder buffer;-- // 6. Let seen EOF be false.- bool seen_eof = false;-- // 7. Let seen arrow be false.- bool seen_arrow = false;-- // 8. Let cue be null.- Optional<ParsedCue> cue;-- // FIXME: 9. Let stylesheet be null.- // FIXME: 10. Let region be null.-- // 11. Loop: Run these substeps in a loop:- while (true) {- // 1. Collect a sequence of code points that are not U+000A LINE FEED (LF) characters. Let line be those- // characters, if any.- line = collect_a_sequence_of_code_points_that_are_not_line_feeds();-- // 2. Increment line count by 1.- ++line_count;-- // 3. If position is past the end of input, let seen EOF be true. Otherwise, the character indicated by position- // is a U+000A LINE FEED (LF) character; advance position to the next character in input.- if (is_past_end())- seen_eof = true;- else- ++m_position;-- // 4. If line contains the three-character substring "-->" (U+002D HYPHEN-MINUS, U+002D HYPHEN-MINUS, U+003E- // GREATER-THAN SIGN), then run these substeps:- if (line.contains(u"-->"sv)) {- // 1. If in header is not set and at least one of the following conditions are true:- // - line count is 1- // - line count is 2 and seen arrow is false- // ...then run these substeps:- if (!in_header && (line_count == 1 || (line_count == 2 && !seen_arrow))) {- // 1. Let seen arrow be true.- seen_arrow = true;-- // 2. Let previous position be position.- previous_position = m_position;-- // 3. Cue creation: Let cue be a new WebVTT cue and initialize it as follows:- // Let cue's text track cue identifier be buffer.- // FIXME: Initialize the remaining cue fields once cue settings are supported.- cue = ParsedCue {};- cue->identifier = buffer.to_string();-- // 4. Collect WebVTT cue timings and settings from line using regions for cue. If that fails, let cue be- // null. Otherwise, let buffer be the empty string and let seen cue be true.- if (!collect_webvtt_cue_timings_and_settings(line, *cue)) {- cue.clear();- } else {- buffer.clear();- m_seen_cue = true;- }- }- // Otherwise, let position be previous position and break out of loop.- else {- m_position = previous_position;- break;- }- }- // 5. Otherwise, if line is the empty string, break out of loop.- else if (line.is_empty()) {- break;- }- // 6. Otherwise, run these substeps:- else {- // 1. If in header is not set and line count is 2, run these substeps:- if (!in_header && line_count == 2) {- // 1. If seen cue is false and buffer starts with the substring "STYLE" (U+0053 LATIN CAPITAL LETTER S,- // U+0054 LATIN CAPITAL LETTER T, U+0059 LATIN CAPITAL LETTER Y, U+004C LATIN CAPITAL LETTER L, U+0045- // LATIN CAPITAL LETTER E), and the remaining characters in buffer (if any) are all ASCII whitespace,- // then run these substeps:- // 2. Otherwise, if seen cue is false and buffer starts with the substring "REGION" (U+0052 LATIN CAPITAL- // LETTER R, U+0045 LATIN CAPITAL LETTER E, U+0047 LATIN CAPITAL LETTER G, U+0049 LATIN CAPITAL LETTER- // I, U+004F LATIN CAPITAL LETTER O, U+004E LATIN CAPITAL LETTER N), and the remaining characters in- // buffer (if any) are all ASCII whitespace, then run these substeps:- if (!m_seen_cue && (is_block_keyword(buffer.view(), u"STYLE"sv) || is_block_keyword(buffer.view(), u"REGION"sv))) {- // FIXME: Create the CSS style sheet or WebVTT region.- // Let buffer be the empty string.- buffer.clear();- }- }-- // 2. If buffer is not the empty string, append a U+000A LINE FEED (LF) character to buffer.- if (!buffer.is_empty())- buffer.append_code_unit('\n');-- // 3. Append line to buffer.- buffer.append(line);-- // 4. Let previous position be position.- previous_position = m_position;- }-- // 7. If seen EOF is true, break out of loop.- if (seen_eof)- break;- }-- // 12. If cue is not null, let the cue text of cue be buffer, and return cue.- if (cue.has_value()) {- cue->text = buffer.to_string();- return cue;- }-- // FIXME: 13. Otherwise, if stylesheet is not null, then Parse a stylesheet from buffer. If it returned a list of- // rules, assign the list as stylesheet's CSS rules; otherwise, set stylesheet's CSS rules to an empty- // list. Finally, return stylesheet.- // FIXME: 14. Otherwise, if region is not null, then collect WebVTT region settings from buffer using region for the- // results. Construct a WebVTT Region Object from region, and return it.-- // 15. Otherwise, return null.- return {};-}--// https://w3c.github.io/webvtt/#webvtt-parser-algorithm-Optional<Vector<ParsedCue>> Parser::parse()-{- Vector<ParsedCue> output;-- // 2. Let position be a pointer into input, initially pointing at the start of the string.- // 3. Let seen cue be false.-- // 4. If input is less than six characters long, then abort these steps. The file does not start with the correct- // WebVTT file signature and was therefore not successfully processed.- if (m_input.length_in_code_units() < 6)- return {};-- // 5. If input is exactly six characters long but does not exactly equal "WEBVTT", then abort these steps. The file- // does not start with the correct WebVTT file signature and was therefore not successfully processed.- // 6. If input is more than six characters long but the first six characters do not exactly equal "WEBVTT", or the- // seventh character is not a U+0020 SPACE character, a U+0009 CHARACTER TABULATION (tab) character, or a U+000A- // LINE FEED (LF) character, then abort these steps. The file does not start with the correct WebVTT file- // signature and was therefore not successfully processed.- if (!m_input.starts_with(u"WEBVTT"sv))- return {};- if (m_input.length_in_code_units() > 6 && !first_is_one_of(m_input.code_unit_at(6), ' ', '\t', '\n'))- return {};-- // 7. Collect a sequence of code points that are not U+000A LINE FEED (LF) characters.- (void)collect_a_sequence_of_code_points_that_are_not_line_feeds();-- // 8. If position is past the end of input, then abort these steps. The file was successfully processed, but it- // contains no useful data and so no WebVTT cues were added to output.- if (is_past_end())- return output;-- // 9. The character indicated by position is a U+000A LINE FEED (LF) character. Advance position to the next- // character in input.- ++m_position;-- // 10. If position is past the end of input, then abort these steps. The file was successfully processed, but it- // contains no useful data and so no WebVTT cues were added to output.- if (is_past_end())- return output;-- // 11. Header: If the character indicated by position is not a U+000A LINE FEED (LF) character, then collect a WebVTT- // block with the in header flag set. Otherwise, advance position to the next character in input.- if (current() != '\n')- (void)collect_a_webvtt_block(true);- else- ++m_position;-- // 12. Collect a sequence of code points that are U+000A LINE FEED (LF) characters.- collect_a_sequence_of_line_feeds();-- // FIXME: 13. Let regions be an empty text track list of regions.-- // 14. Block loop: While position doesn't point past the end of input:- while (!is_past_end()) {- // 1. Collect a WebVTT block, and let block be the returned value.- auto block = collect_a_webvtt_block(false);-- // 2. If block is a WebVTT cue, add block to the text track list of cues output.- if (block.has_value())- output.append(block.release_value());-- // FIXME: 3. Otherwise, if block is a CSS style sheet, add block to stylesheets.- // FIXME: 4. Otherwise, if block is a WebVTT region object, add block to regions.-- // 5. Collect a sequence of code points that are U+000A LINE FEED (LF) characters.- collect_a_sequence_of_line_feeds();- }-- // 15. End: The file has ended. Abort these steps. The WebVTT parser has finished. The file was successfully- // processed.- return output;-}+extern "C" {+// Defined in Bindings/Rust/src/web_vtt/exports.rs.+bool web_vtt_parse_webvtt_file(u8 const* bytes, size_t length, void* ctx, void (*on_cue)(void* ctx, FlatPtr identifier, double start_time, double end_time, FlatPtr text));}// https://w3c.github.io/webvtt/#webvtt-parserOptional<Vector<ParsedCue>> parse_webvtt_file(ReadonlyBytes bytes){- // A WebVTT parser, given an input byte stream, a text track list of cues output, and a collection of CSS style- // sheets stylesheets, must decode the byte stream using the UTF-8 decode algorithm, and then must parse the resulting- // string according to the WebVTT parser algorithm below.- auto decoded = Utf16String::from_utf8_with_replacement_character(StringView { bytes }, Utf16String::WithBOMHandling::Yes);-- // 1. Let input be the string being parsed, after conversion to Unicode, and with the following transformations- // applied:- // - Replace all U+0000 NULL characters by U+FFFD REPLACEMENT CHARACTERs.- // - Replace each U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pair by a single U+000A LINE FEED (LF)- // character.- // - Replace all remaining U+000D CARRIAGE RETURN characters by U+000A LINE FEED (LF) characters.- auto view = decoded.utf16_view();- Utf16StringBuilder builder;- for (size_t i = 0; i < view.length_in_code_units(); ++i) {- auto code_unit = view.code_unit_at(i);- if (code_unit == 0) {- builder.append_code_unit(0xFFFD);- } else if (code_unit == '\r') {- if (i + 1 < view.length_in_code_units() && view.code_unit_at(i + 1) == '\n')- ++i;- builder.append_code_unit('\n');- } else {- builder.append_code_unit(code_unit);- }- }- auto input = builder.to_string();-- Parser parser { input.utf16_view() };- return parser.parse();+ Vector<ParsedCue> cues;+ auto on_cue = [](void* ctx, FlatPtr identifier, double start_time, double end_time, FlatPtr text) {+ static_cast<Vector<ParsedCue>*>(ctx)->append({+ .identifier = Utf16String::adopt_raw(identifier),+ .start_time = start_time,+ .end_time = end_time,+ .text = Utf16String::adopt_raw(text),+ });+ };+ if (!web_vtt_parse_webvtt_file(bytes.data(), bytes.size(), &cues, on_cue))+ return {};+ return cues;}}diff --git a/Libraries/LibWeb/WebVTT/VTTCue.cpp b/Libraries/LibWeb/WebVTT/VTTCue.cppindex 1065ce0fca8..6c3b3fe0ed1 100644--- a/Libraries/LibWeb/WebVTT/VTTCue.cpp+++ b/Libraries/LibWeb/WebVTT/VTTCue.cpp@@ -4,221 +4,22 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibGC/Heap.h>-#include <LibWeb/HTML/Window.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/VM.h>#include <LibWeb/WebVTT/VTTCue.h>namespace Web::WebVTT {-GC_DEFINE_ALLOCATOR(VTTCue);+extern "C" {-// https://w3c.github.io/webvtt/#dom-vttcue-vttcue-WebIDL::ExceptionOr<GC::Ref<VTTCue>> VTTCue::create(double start_time, double end_time, Utf16String const& text)-{- // 1. Create a new WebVTT cue. Let cue be that WebVTT cue.- auto cue = GC::Heap::the().allocate<VTTCue>(nullptr);-- // 2. Let cue’s text track cue start time be the value of the startTime argument.- cue->m_start_time = start_time;-- // 3. If the value of the endTime argument is negative Infinity or a Not-a-Number (NaN) value, then throw a TypeError exception.- // Otherwise, let cue’s text track cue end time be the value of the endTime argument.- if (end_time == -AK::Infinity<double> || isnan(end_time))- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "End time is negative infinity or NaN"_utf16 };- cue->m_end_time = end_time;-- // 4. Let cue’s cue text be the value of the text argument, and let the rules for extracting the chapter title be the WebVTT rules- // for extracting the chapter title.- cue->m_text = text;- // FIXME: let the rules for extracting the chapter title be the WebVTT rules for extracting the chapter title.-- // 5. Let cue’s text track cue identifier be the empty string.- cue->m_identifier = {};-- // 6. Let cue’s text track cue pause-on-exit flag be false.- cue->m_pause_on_exit = false;-- // 7. Let cue’s WebVTT cue region be null.- cue->m_region = nullptr;-- // 8. Let cue’s WebVTT cue writing direction be horizontal.- cue->m_writing_direction = WritingDirection::Horizontal;-- // 9. Let cue’s WebVTT cue snap-to-lines flag be true.- cue->m_snap_to_lines = true;-- // 10. Let cue’s WebVTT cue line be auto.- cue->m_line = AutoKeyword::Auto;-- // 11. Let cue’s WebVTT cue line alignment be start alignment.- cue->m_line_alignment = LineAlignSetting::Start;-- // 12. Let cue’s WebVTT cue position be auto.- cue->m_position = AutoKeyword::Auto;-- // 13. Let cue’s WebVTT cue position alignment be auto.- cue->m_position_alignment = PositionAlignSetting::Auto;-- // 14. Let cue’s WebVTT cue size be 100.- cue->m_size = 100;-- // 15. Let cue’s WebVTT cue text alignment be center alignment.- cue->m_text_alignment = AlignSetting::Center;-- // 16. Return the VTTCue object representing cue.- return cue;-}--VTTCue::VTTCue(GC::Ptr<HTML::TextTrack> track)- : HTML::TextTrackCue(track)-{-}--void VTTCue::visit_edges(Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_region);-}--// https://w3c.github.io/webvtt/#dom-vttcue-vertical-DirectionSetting VTTCue::vertical() const-{- switch (m_writing_direction) {- case WritingDirection::Horizontal:- return DirectionSetting::Empty;- case WritingDirection::VerticalGrowingLeft:- return DirectionSetting::Rl;- case WritingDirection::VerticalGrowingRight:- return DirectionSetting::Lr;- }- VERIFY_NOT_REACHED();-}--// https://w3c.github.io/webvtt/#dom-vttcue-vertical-void VTTCue::set_vertical(DirectionSetting vertical)-{- switch (vertical) {- case DirectionSetting::Empty:- m_writing_direction = WritingDirection::Horizontal;- break;- case DirectionSetting::Rl:- m_writing_direction = WritingDirection::VerticalGrowingLeft;- break;- case DirectionSetting::Lr:- m_writing_direction = WritingDirection::VerticalGrowingRight;- break;- }-}--VTTCue::LineAndPositionSetting VTTCue::line() const-{- return m_line;-}--void VTTCue::set_line(LineAndPositionSetting line)-{- m_line = line;-}--LineAlignSetting VTTCue::line_align() const-{- return m_line_alignment;+// Defined in Bindings/Rust/src/web_vtt/exports.rs.+void* web_vtt_cue_create(JSVM*, double start_time, double end_time, FlatPtr text);}-void VTTCue::set_line_align(LineAlignSetting line_align)+GC::Ref<VTTCue> VTTCue::create(double start_time, double end_time, Utf16String const& text){- m_line_alignment = line_align;-}--VTTCue::LineAndPositionSetting VTTCue::position() const-{- return m_position;-}--void VTTCue::set_position(LineAndPositionSetting position)-{- m_position = position;-}--PositionAlignSetting VTTCue::position_align() const-{- return m_position_alignment;-}--void VTTCue::set_position_align(PositionAlignSetting position_align)-{- m_position_alignment = position_align;-}--AlignSetting VTTCue::align() const-{- return m_text_alignment;-}--void VTTCue::set_align(AlignSetting align)-{- m_text_alignment = align;-}--// https://w3c.github.io/webvtt/#cue-computed-line-double VTTCue::computed_line()-{- // 1. If the line is numeric, the WebVTT cue snap-to-lines flag of the WebVTT cue is false, and the line is negative- // or greater than 100, then return 100 and abort these steps.- if (m_line.has<double>() && !m_snap_to_lines && (m_line.get<double>() < 0 || m_line.get<double>() > 100))- return 100;-- // 2. If the line is numeric, return the value of the WebVTT cue line and abort these steps. (Either the WebVTT cue- // snap-to-lines flag is true, so any value, not just those in the range 0..100, is valid, or the value is in the- // range 0..100 and is thus valid regardless of the value of that flag.)- if (m_line.has<double>())- return m_line.get<double>();-- // 3. If the WebVTT cue snap-to-lines flag of the WebVTT cue is false, return the value 100 and abort these steps.- // (The line is the special value auto.)- if (!m_snap_to_lines)- return 100;-- // FIXME: 4. Let cue be the WebVTT cue.-- // FIXME: 5. If cue is not in a list of cues of a text track, or if that text track is not in the list of text tracks of- // a media element, return −1 and abort these steps.-- // FIXME: 6. Let track be the text track whose list of cues the cue is in.-- // FIXME: 7. Let n be the number of text tracks whose text track mode is showing and that are in the media element’s list- // of text tracks before track.- auto n = 0;-- // 8. Increment n by one.- n++;-- // 9. Negate n.- n = -n;-- // 10. Return n.- dbgln("FIXME: Stubbed VTTCue.computed_line()");- return n;-}--// https://w3c.github.io/webvtt/#cue-computed-position-double VTTCue::computed_position()-{- // 1. If the position is numeric between 0 and 100, then return the value of the position and abort these steps.- // (Otherwise, the position is the special value auto.)- if (m_position.has<double>() && m_position.get<double>() >= 0 && m_position.get<double>() <= 100)- return m_position.get<double>();-- // 2. If the cue text alignment is left, return 0 and abort these steps.- if (m_text_alignment == AlignSetting::Left)- return 0;-- // 3. If the cue text alignment is right, return 100 and abort these steps.- if (m_text_alignment == AlignSetting::Right)- return 100;-- // 4. Otherwise, return 50 and abort these steps.- return 50;+ auto* cue = web_vtt_cue_create(JS::HostABI::vm_to_abi(JS::VM::the()), start_time, end_time, text.raw_identity());+ return GC::Ref { *static_cast<VTTCue*>(cue) };}}diff --git a/Libraries/LibWeb/WebVTT/VTTCue.h b/Libraries/LibWeb/WebVTT/VTTCue.hindex 2c1157e08f5..43116cc6b05 100644--- a/Libraries/LibWeb/WebVTT/VTTCue.h+++ b/Libraries/LibWeb/WebVTT/VTTCue.h@@ -7,110 +7,20 @@#pragma once#include <AK/Utf16String.h>+#include <LibGC/Ptr.h>#include <LibWeb/Bindings/VTTCue.h>#include <LibWeb/HTML/TextTrackCue.h>-#include <LibWeb/WebVTT/VTTRegion.h>-#include <LibWebCommon/WebIDL/Types.h>namespace Web::WebVTT {-using AutoKeyword = Bindings::AutoKeyword;-using DirectionSetting = Bindings::DirectionSetting;-using LineAlignSetting = Bindings::LineAlignSetting;-using PositionAlignSetting = Bindings::PositionAlignSetting;-using AlignSetting = Bindings::AlignSetting;-// https://w3c.github.io/webvtt/#vttcueclass VTTCue final : public HTML::TextTrackCue {- WEB_WRAPPABLE(VTTCue, HTML::TextTrackCue);- GC_DECLARE_ALLOCATOR(VTTCue);+ WEB_RUST_INTERFACE(VTTCue, vtt_cue)public:- static constexpr size_t region_offset() { return offsetof(VTTCue, m_region); }- enum class WritingDirection : u8 {- // https://w3c.github.io/webvtt/#webvtt-cue-horizontal-writing-direction- Horizontal,-- // https://w3c.github.io/webvtt/#webvtt-cue-vertical-growing-left-writing-direction- VerticalGrowingLeft,-- // https://w3c.github.io/webvtt/#webvtt-cue-vertical-growing-right-writing-direction- VerticalGrowingRight,- };-- using LineAndPositionSetting = Variant<double, AutoKeyword>;-- static WebIDL::ExceptionOr<GC::Ref<VTTCue>> create(double start_time, double end_time, Utf16String const& text);- virtual ~VTTCue() override = default;-- GC::Ptr<VTTRegion> region() const { return m_region; }- void set_region(GC::Ptr<VTTRegion> region) { m_region = region; }-- DirectionSetting vertical() const;- void set_vertical(DirectionSetting);-- bool snap_to_lines() const { return m_snap_to_lines; }- void set_snap_to_lines(bool snap_to_lines) { m_snap_to_lines = snap_to_lines; }-- LineAndPositionSetting line() const;- void set_line(LineAndPositionSetting);-- LineAlignSetting line_align() const;- void set_line_align(LineAlignSetting);-- LineAndPositionSetting position() const;- void set_position(LineAndPositionSetting);-- PositionAlignSetting position_align() const;- void set_position_align(PositionAlignSetting);-- double size() const { return m_size; }- void set_size(double size) { m_size = size; }-- AlignSetting align() const;- void set_align(AlignSetting);-- Utf16String const& text() const { return m_text; }- void set_text(Utf16String const& text) { m_text = text; }--protected:- double computed_line();- double computed_position();--private:- VTTCue(GC::Ptr<HTML::TextTrack>);-- virtual void visit_edges(Visitor&) override;-- // https://w3c.github.io/webvtt/#cue-text- Utf16String m_text;-- // https://w3c.github.io/webvtt/#webvtt-cue-writing-direction- WritingDirection m_writing_direction { WritingDirection::Horizontal };-- // https://w3c.github.io/webvtt/#webvtt-cue-snap-to-lines-flag- bool m_snap_to_lines { true };-- // https://w3c.github.io/webvtt/#webvtt-cue-line- LineAndPositionSetting m_line { AutoKeyword::Auto };-- // https://w3c.github.io/webvtt/#webvtt-cue-line-alignment- LineAlignSetting m_line_alignment { LineAlignSetting::Start };-- // https://w3c.github.io/webvtt/#webvtt-cue-position- LineAndPositionSetting m_position { AutoKeyword::Auto };-- // https://w3c.github.io/webvtt/#webvtt-cue-position-alignment- PositionAlignSetting m_position_alignment { PositionAlignSetting::Auto };-- // https://w3c.github.io/webvtt/#webvtt-cue-size- double m_size { 100 };-- // https://w3c.github.io/webvtt/#webvtt-cue-text-alignment- AlignSetting m_text_alignment { AlignSetting::Center };-- // https://w3c.github.io/webvtt/#webvtt-cue-region- GC::Ptr<VTTRegion> m_region;+ // https://w3c.github.io/webvtt/#dom-vttcue-vttcue+ // NB: The end time must be neither negative infinity nor NaN.+ static GC::Ref<VTTCue> create(double start_time, double end_time, Utf16String const& text);};}diff --git a/Libraries/LibWeb/WebVTT/VTTCue.idl b/Libraries/LibWeb/WebVTT/VTTCue.idlindex 2e413e0f371..24f10ca72c1 100644--- a/Libraries/LibWeb/WebVTT/VTTCue.idl+++ b/Libraries/LibWeb/WebVTT/VTTCue.idl@@ -6,10 +6,10 @@ enum PositionAlignSetting { "line-left", "center", "line-right", "auto" };enum AlignSetting { "start", "center", "end", "left", "right" };// https://w3c.github.io/webvtt/#vttcue-[Exposed=Window]+[Exposed=Window, ImplementedIn=Rust]interface VTTCue : TextTrackCue {constructor(double startTime, unrestricted double endTime, DOMString text);- [DirectGetter] attribute VTTRegion? region;+ attribute VTTRegion? region;attribute DirectionSetting vertical;attribute boolean snapToLines;attribute LineAndPositionSetting line;diff --git a/Libraries/LibWeb/WebVTT/VTTRegion.cpp b/Libraries/LibWeb/WebVTT/VTTRegion.cppdeleted file mode 100644index 6f8e95e4923..00000000000--- a/Libraries/LibWeb/WebVTT/VTTRegion.cpp+++ /dev/null@@ -1,128 +0,0 @@-/*- * Copyright (c) 2024, Jamie Mansfield <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibWeb/HTML/Window.h>-#include <LibWeb/WebVTT/VTTRegion.h>--namespace Web::WebVTT {--GC_DEFINE_ALLOCATOR(VTTRegion);--// https://w3c.github.io/webvtt/#dom-vttregion-vttregion-GC::Ref<VTTRegion> VTTRegion::create()-{- // 1. Create a new WebVTT region. Let region be that WebVTT region.- auto region = GC::Heap::the().allocate<VTTRegion>();-- // 2. Let region’s WebVTT region identifier be the empty string.- region->m_identifier = {};-- // 3. Let region’s WebVTT region width be 100.- region->m_width = 100;-- // 4. Let region’s WebVTT region lines be 3.- region->m_lines = 3;-- // 5. Let region’s text track region regionAnchorX be 0.- region->m_anchor_x = 0;-- // 6. Let region’s text track region regionAnchorY be 100.- region->m_anchor_y = 100;-- // 7. Let region’s text track region viewportAnchorX be 0.- region->m_viewport_anchor_x = 0;-- // 8. Let region’s text track region viewportAnchorY be 100.- region->m_viewport_anchor_y = 100;-- // 9. Let region’s WebVTT region scroll be the empty string.- region->m_scroll_setting = ScrollSetting::Empty;-- // 10. Return the VTTRegion object representing region.- return region;-}--VTTRegion::VTTRegion()-{-}--ScrollSetting VTTRegion::scroll() const-{- return m_scroll_setting;-}--void VTTRegion::set_scroll(ScrollSetting scroll)-{- m_scroll_setting = scroll;-}--static GC::Ref<WebIDL::DOMException> create_region_range_error()-{- return WebIDL::IndexSizeError::create("Value is negative or greater than 100"_utf16);-}--// https://w3c.github.io/webvtt/#dom-vttregion-width-WebIDL::ExceptionOr<void> VTTRegion::set_width(double width)-{- // On setting, if the new value is negative or greater than 100, then an IndexSizeError exception must be thrown.- if (width < 0 || width > 100)- return create_region_range_error();-- // Otherwise, the WebVTT region width must be set to the new value.- m_width = width;- return {};-}--// https://w3c.github.io/webvtt/#dom-vttregion-regionanchorx-WebIDL::ExceptionOr<void> VTTRegion::set_region_anchor_x(double region_anchor_x)-{- // On setting, if the new value is negative or greater than 100, then an IndexSizeError exception must be thrown.- if (region_anchor_x < 0 || region_anchor_x > 100)- return create_region_range_error();-- // Otherwise, the WebVTT region anchor X distance must be set to the new value.- m_anchor_x = region_anchor_x;- return {};-}--// https://w3c.github.io/webvtt/#dom-vttregion-regionanchory-WebIDL::ExceptionOr<void> VTTRegion::set_region_anchor_y(double region_anchor_y)-{- // On setting, if the new value is negative or greater than 100, then an IndexSizeError exception must be thrown.- if (region_anchor_y < 0 || region_anchor_y > 100)- return create_region_range_error();-- // Otherwise, the WebVTT region anchor Y distance must be set to the new value.- m_anchor_y = region_anchor_y;- return {};-}--// https://w3c.github.io/webvtt/#dom-vttregion-viewportanchorx-WebIDL::ExceptionOr<void> VTTRegion::set_viewport_anchor_x(double viewport_anchor_x)-{- // On setting, if the new value is negative or greater than 100, then an IndexSizeError exception must be thrown.- if (viewport_anchor_x < 0 || viewport_anchor_x > 100)- return create_region_range_error();-- // Otherwise, the WebVTT region viewport anchor X distance must be set to the new value.- m_viewport_anchor_x = viewport_anchor_x;- return {};-}--// https://w3c.github.io/webvtt/#dom-vttregion-viewportanchory-WebIDL::ExceptionOr<void> VTTRegion::set_viewport_anchor_y(double viewport_anchor_y)-{- // On setting, if the new value is negative or greater than 100, then an IndexSizeError exception must be thrown.- if (viewport_anchor_y < 0 || viewport_anchor_y > 100)- return create_region_range_error();-- // Otherwise, the WebVTT region viewport anchor Y distance must be set to the new value.- m_viewport_anchor_y = viewport_anchor_y;- return {};-}--}diff --git a/Libraries/LibWeb/WebVTT/VTTRegion.h b/Libraries/LibWeb/WebVTT/VTTRegion.hdeleted file mode 100644index 968c18707cb..00000000000--- a/Libraries/LibWeb/WebVTT/VTTRegion.h+++ /dev/null@@ -1,75 +0,0 @@-/*- * Copyright (c) 2024, Jamie Mansfield <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibJS/Forward.h>-#include <LibWeb/Bindings/VTTRegion.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWebCommon/WebIDL/Types.h>--namespace Web::WebVTT {--using ScrollSetting = Bindings::ScrollSetting;--// https://w3c.github.io/webvtt/#vttregion-class VTTRegion final : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(VTTRegion, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(VTTRegion);--public:- static GC::Ref<VTTRegion> create();- virtual ~VTTRegion() override = default;-- Utf16String const& id() const { return m_identifier; }- void set_id(Utf16String const& id) { m_identifier = id; }-- double width() const { return m_width; }- WebIDL::ExceptionOr<void> set_width(double width);-- WebIDL::UnsignedLong lines() const { return m_lines; }- void set_lines(WebIDL::UnsignedLong lines) { m_lines = lines; }-- double region_anchor_x() const { return m_anchor_x; }- WebIDL::ExceptionOr<void> set_region_anchor_x(double region_anchor_x);-- double region_anchor_y() const { return m_anchor_y; }- WebIDL::ExceptionOr<void> set_region_anchor_y(double region_anchor_y);-- double viewport_anchor_x() const { return m_viewport_anchor_x; }- WebIDL::ExceptionOr<void> set_viewport_anchor_x(double viewport_anchor_x);-- double viewport_anchor_y() const { return m_viewport_anchor_y; }- WebIDL::ExceptionOr<void> set_viewport_anchor_y(double viewport_anchor_y);-- ScrollSetting scroll() const;- void set_scroll(ScrollSetting);--private:- VTTRegion();-- // https://w3c.github.io/webvtt/#webvtt-region-identifier- Utf16String m_identifier {};-- // https://w3c.github.io/webvtt/#webvtt-region-width- double m_width { 100 };-- // https://w3c.github.io/webvtt/#webvtt-region-lines- WebIDL::UnsignedLong m_lines { 3 };-- // https://w3c.github.io/webvtt/#webvtt-region-anchor- double m_anchor_x { 0 };- double m_anchor_y { 100 };-- // https://w3c.github.io/webvtt/#webvtt-region-viewport-anchor- double m_viewport_anchor_x { 0 };- double m_viewport_anchor_y { 100 };-- // https://w3c.github.io/webvtt/#webvtt-region-scroll- ScrollSetting m_scroll_setting { ScrollSetting::Empty };-};--}diff --git a/Libraries/LibWeb/WebVTT/VTTRegion.idl b/Libraries/LibWeb/WebVTT/VTTRegion.idlindex 0561f094317..620cdea001d 100644--- a/Libraries/LibWeb/WebVTT/VTTRegion.idl+++ b/Libraries/LibWeb/WebVTT/VTTRegion.idl@@ -2,7 +2,7 @@enum ScrollSetting { "", "up" };// https://w3c.github.io/webvtt/#vttregion-[Exposed=Window]+[Exposed=Window, ImplementedIn=Rust]interface VTTRegion {constructor();attribute DOMString id;