Truly independent web browser
LibCompositing+Compositor: Replay the WebGL command stream in Rust
Aliaksandr Kalenikdaa7ca3a038a
diff --git a/Cargo.lock b/Cargo.lockindex ee6424b66be..8c5fc99be68 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -628,6 +628,7 @@ dependencies = ["libgfx_rust","libipc_rust","rustc-demangle",+ "serde_json",][[package]]diff --git a/Libraries/LibCompositing/Rust/generate/webgl_wire.rs b/Libraries/LibCompositing/Rust/generate/webgl_wire.rsindex 021d492901c..dd7f1231c9a 100644--- a/Libraries/LibCompositing/Rust/generate/webgl_wire.rs+++ b/Libraries/LibCompositing/Rust/generate/webgl_wire.rs@@ -73,7 +73,22 @@ fn write_struct(out: &mut String, rust_name: &str, layout: &WireStruct) {for field in &fields {writeln!(out, " {}: {},", field.name, field.zero).unwrap();}- out.push_str(" };\n }\n");+ out.push_str(" };\n");+ let bool_field_offsets: Vec<String> = layout+ .fields+ .iter()+ .filter(|field| field.wire_type == WireType::Bool)+ .map(|field| field.offset.to_string())+ .collect();+ if !bool_field_offsets.is_empty() {+ writeln!(+ out,+ " const BOOL_FIELD_OFFSETS: &'static [usize] = &[{}];",+ bool_field_offsets.join(", ")+ )+ .unwrap();+ }+ out.push_str(" }\n");out.push_str(" const _: () = {\n");writeln!(out, " assert!(size_of::<{rust_name}>() == {});", layout.size).unwrap();writeln!(@@ -102,6 +117,12 @@ fn write_type_enum(out: &mut String, enum_name: &str, count_name: &str, descriptwriteln!(out, " {name},").unwrap();}out.push_str("}\n\n");+ writeln!(out, "impl {enum_name} {{").unwrap();+ out.push_str(" pub fn from_number(number: u16) -> Option<Self> {\n Some(match number {\n");+ for (number, name) in names.iter().enumerate() {+ writeln!(out, " {number} => Self::{name},").unwrap();+ }+ out.push_str(" _ => return None,\n })\n }\n}\n\n");// NB: Only the tests of the vocabulary ask how many types there are.writeln!(out, "#[cfg(test)]\npub const {count_name}: u16 = {};\n", names.len()).unwrap();}diff --git a/Libraries/LibCompositing/Rust/generate/webgl_wire_model.rs b/Libraries/LibCompositing/Rust/generate/webgl_wire_model.rsindex 7db8c3d7704..3db9582af7f 100644--- a/Libraries/LibCompositing/Rust/generate/webgl_wire_model.rs+++ b/Libraries/LibCompositing/Rust/generate/webgl_wire_model.rs@@ -21,6 +21,23 @@ pub enum Category {BuiltinCommand,}+/// The object that the replayer passes for the object id 0.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum DefaultObject {+ Framebuffer,+ Renderbuffer,+}++/// A factor of the number of bytes that a pointer argument points at.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum PayloadFactor {+ Constant(u64),+ /// The value of the argument of this index.+ Argument(usize),+ /// 4 where the argument of this index is GL_COLOR, and 1 otherwise.+ ColorBufferComponents(usize),+}+#[derive(Debug)]pub struct Argument {pub cpp_type: String,@@ -32,6 +49,9 @@ pub struct Argument {pub is_offset: bool,pub is_string: bool,pub is_nullable: bool,+ pub zero_means_default: Option<DefaultObject>,+ /// What the replayer passes instead of what the recorder sent.+ pub host_override: Option<String>,}impl Argument {@@ -64,6 +84,7 @@ pub struct Function {/// The built-in commands, which are no GL functions, have none.pub return_type: Option<String>,pub arguments: Vec<Argument>,+ pub deletes_objects: bool,wire_command: Option<Vec<FieldSpec>>,wire_request: Option<Vec<FieldSpec>>,wire_reply: Option<Vec<FieldSpec>>,@@ -74,7 +95,6 @@ const FUNCTION_KEYS: [&str; 8] = ["category","return","args",- // What the replayer does with the objects that a function deletes, which the recorder has no part in."deletes_objects","wire_command","wire_request",@@ -90,7 +110,6 @@ const ARGUMENT_KEYS: [&str; 10] = ["offset","string","nullable",- // How the replayer resolves an argument, which the recorder has no part in."zero_means_default","host_override",];@@ -128,7 +147,19 @@ fn parse_argument(value: &Value, function_name: &str) -> Result<Argument, Stringlet what = format!("an argument of {function_name}");let object = value.as_object().ok_or_else(|| format!("{what} is not an object"))?;reject_unknown_keys(object, &ARGUMENT_KEYS, &what)?;+ let zero_means_default = match string_member(object, "zero_means_default", &what)?.as_deref() {+ None => None,+ Some("default_framebuffer") => Some(DefaultObject::Framebuffer),+ Some("default_renderbuffer") => Some(DefaultObject::Renderbuffer),+ Some(other) => {+ return Err(format!(+ "{what} has the default object {other:?}, which the model does not know"+ ));+ }+ };Ok(Argument {+ zero_means_default,+ host_override: string_member(object, "host_override", &what)?,cpp_type: required_string_member(object, "type", &what)?,name: required_string_member(object, "name", &what)?,payload: string_member(object, "payload", &what)?,@@ -195,6 +226,7 @@ fn parse_function(value: &Value) -> Result<Function, String> {let function = Function {return_type: string_member(object, "return", &name)?,arguments,+ deletes_objects: flag(object, "deletes_objects", &name)?,wire_command: parse_wire_fields(object, "wire_command", &name)?,wire_request: parse_wire_fields(object, "wire_request", &name)?,wire_reply: parse_wire_fields(object, "wire_reply", &name)?,@@ -275,6 +307,52 @@ impl Function {self.category == Category::Sync || self.wire_request.is_some()}+ /// The factors of the number of bytes that an argument with a payload points at.+ pub fn payload_size(&self, argument: &Argument) -> Result<Vec<PayloadFactor>, String> {+ let payload = argument.payload.as_deref().ok_or_else(|| {+ format!(+ "the argument {} of {} points at data without a size",+ argument.name, self.name+ )+ })?;+ let unknown = |factor: &str| {+ format!(+ "the size {payload:?} of the argument {} of {} has the factor {factor:?}, which the model does not know",+ argument.name, self.name+ )+ };+ let argument_index = |name: &str| {+ self.arguments+ .iter()+ .position(|other| other.name == name && !other.is_out && !other.is_pointer())+ };+ payload+ .split(" * ")+ .map(|factor| {+ if let Ok(constant) = factor.parse() {+ return Ok(PayloadFactor::Constant(constant));+ }+ if let Some(gl_type) = factor.strip_prefix("sizeof(").and_then(|rest| rest.strip_suffix(')')) {+ let size = match gl_type {+ "GLchar" | "GLboolean" => 1,+ "GLint" | "GLuint" | "GLfloat" | "GLenum" => 4,+ "GLint64" => 8,+ _ => return Err(unknown(factor)),+ };+ return Ok(PayloadFactor::Constant(size));+ }+ if factor == "(buffer == GL_COLOR ? 4 : 1)" {+ return argument_index("buffer")+ .map(PayloadFactor::ColorBufferComponents)+ .ok_or_else(|| unknown(factor));+ }+ argument_index(factor)+ .map(PayloadFactor::Argument)+ .ok_or_else(|| unknown(factor))+ })+ .collect()+ }+fn unhandled_pointer(&self, argument: &Argument) -> String {format!("the model of the WebGL functions does not handle the pointer argument {} of {}",diff --git a/Libraries/LibCompositing/Rust/generate/webgl_wire_model_tests.rs b/Libraries/LibCompositing/Rust/generate/webgl_wire_model_tests.rsindex 8fc103f6e11..3527f86dacc 100644--- a/Libraries/LibCompositing/Rust/generate/webgl_wire_model_tests.rs+++ b/Libraries/LibCompositing/Rust/generate/webgl_wire_model_tests.rs@@ -162,3 +162,46 @@ fn a_name_hash_is_fnv_1a() {assert_eq!(wire_layout_name_hash("a"), 0xE40C_292C);assert_eq!(wire_layout_name_hash("Commands::ActiveTexture"), 0x9B0F_0F7C);}++#[test]+fn what_the_replayer_needs_is_read_from_the_json() {+ let functions = parse_functions(+ r#"[+ {"name": "glDeleteBuffers", "return": "void", "category": "command", "deletes_objects": true, "args": [+ {"type": "GLsizei", "name": "n"},+ {"type": "GLuint const*", "name": "buffers", "object": true, "payload": "n * sizeof(GLuint)"}]},+ {"name": "glBindFramebuffer", "return": "void", "category": "command", "args": [+ {"type": "GLenum", "name": "target"},+ {"type": "GLuint", "name": "framebuffer", "object": true, "zero_means_default": "default_framebuffer"}]},+ {"name": "glClientWaitSync", "return": "GLenum", "category": "sync", "args": [+ {"type": "GLsync", "name": "sync", "object": true},+ {"type": "GLuint64", "name": "timeout", "host_override": "0"}]},+ {"name": "glClearBufferfv", "return": "void", "category": "command", "args": [+ {"type": "GLenum", "name": "buffer"},+ {"type": "GLfloat const*", "name": "value", "payload": "(buffer == GL_COLOR ? 4 : 1) * sizeof(GLfloat)"}]}+ ]"#,+ )+ .unwrap();+ assert!(functions[0].deletes_objects);+ assert!(!functions[1].deletes_objects);+ assert_eq!(+ functions[0].payload_size(&functions[0].arguments[1]).unwrap(),+ [PayloadFactor::Argument(0), PayloadFactor::Constant(4)]+ );+ assert_eq!(+ functions[1].arguments[1].zero_means_default,+ Some(DefaultObject::Framebuffer)+ );+ assert_eq!(functions[2].arguments[1].host_override.as_deref(), Some("0"));+ assert_eq!(+ functions[3].payload_size(&functions[3].arguments[1]).unwrap(),+ [PayloadFactor::ColorBufferComponents(0), PayloadFactor::Constant(4)]+ );+ let unknown_default = r#"[{"name": "glBindTexture", "return": "void", "category": "command", "args": [+ {"type": "GLuint", "name": "texture", "object": true, "zero_means_default": "default_texture"}]}]"#;+ assert!(+ parse_functions(unknown_default)+ .unwrap_err()+ .contains("default object \"default_texture\"")+ );+}diff --git a/Libraries/LibCompositing/Rust/src/display_list/commands.rs b/Libraries/LibCompositing/Rust/src/display_list/commands.rsindex cfe38cb9384..8d4ab0ebbfc 100644--- a/Libraries/LibCompositing/Rust/src/display_list/commands.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/commands.rs@@ -304,7 +304,7 @@ impl FfiBytes for FontResourceId {}}-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Encode, Decode)]#[repr(transparent)]pub struct ImageFrameResourceId(pub u64);@@ -315,7 +315,7 @@ impl FfiBytes for ImageFrameResourceId {}}-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Encode, Decode)]#[repr(transparent)]pub struct VideoSinkHandle(pub u64);diff --git a/Libraries/LibCompositing/Rust/src/webgl/mod.rs b/Libraries/LibCompositing/Rust/src/webgl/mod.rsindex 9d05fe65c4a..1fae08d0b31 100644--- a/Libraries/LibCompositing/Rust/src/webgl/mod.rs+++ b/Libraries/LibCompositing/Rust/src/webgl/mod.rs@@ -7,9 +7,25 @@//! The WebGL command stream that WebContent records and the Compositor replays, as Libraries/LibCompositing/WebGL///! GLFunctions.json defines it.+use libipc_rust::wire::{Decode, Encode};++use crate::display_list::commands::{ImageFrameResourceId, VideoSinkHandle};++pub mod texture_upload;pub mod vocabulary;pub mod wire;+/// What an upload of an image to a texture takes the pixels of: an image frame that WebContent registered, or a frame of+/// a video that the Compositor holds for it.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Encode, Decode)]+pub enum ImageSource {+ RegisteredImageFrame(ImageFrameResourceId),+ HeldVideoFrame {+ sink_handle: VideoSinkHandle,+ generation: u64,+ },+}+/// The `u64` that the replayer stores the sequence number of the last executed flush in is at the start of the shared/// command buffer, before the region of records.pub const SHARED_DATA_REGION_OFFSET: usize = 128;diff --git a/Libraries/LibCompositing/Rust/src/webgl/texture_upload.rs b/Libraries/LibCompositing/Rust/src/webgl/texture_upload.rsnew file mode 100644index 00000000000..9854f523c71--- /dev/null+++ b/Libraries/LibCompositing/Rust/src/webgl/texture_upload.rs@@ -0,0 +1,69 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The pixel formats that an image is converted to for a texture upload of a format and a type.++const GL_ALPHA: u32 = 0x1906;+const GL_RGB: u32 = 0x1907;+const GL_RGBA: u32 = 0x1908;+const GL_LUMINANCE: u32 = 0x1909;+const GL_LUMINANCE_ALPHA: u32 = 0x190A;+const GL_UNSIGNED_BYTE: u32 = 0x1401;+const GL_UNSIGNED_SHORT_4_4_4_4: u32 = 0x8033;+const GL_UNSIGNED_SHORT_5_5_5_1: u32 = 0x8034;+const GL_UNSIGNED_SHORT_5_6_5: u32 = 0x8363;++/// `Gfx::ExportFormat`.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+#[repr(u8)]+pub enum ExportFormat {+ Luminance8,+ LuminanceAlpha88,+ Alpha8,+ RGB565,+ RGBA5551,+ RGBA4444,+ RGB888,+ RGBA8888,+}++pub fn texture_export_format(format: u32, r#type: u32) -> Option<ExportFormat> {+ Some(match (format, r#type) {+ (GL_RGB, GL_UNSIGNED_BYTE) => ExportFormat::RGB888,+ (GL_RGB, GL_UNSIGNED_SHORT_5_6_5) => ExportFormat::RGB565,+ (GL_RGBA, GL_UNSIGNED_BYTE) => ExportFormat::RGBA8888,+ // FIXME: This is not exactly the same as RGBA.+ (GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4) => ExportFormat::RGBA4444,+ (GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1) => ExportFormat::RGBA5551,+ (GL_ALPHA, GL_UNSIGNED_BYTE) => ExportFormat::Alpha8,+ (GL_LUMINANCE, GL_UNSIGNED_BYTE) => ExportFormat::Luminance8,+ (GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE) => ExportFormat::LuminanceAlpha88,+ _ => return None,+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn only_the_formats_and_types_that_an_image_converts_to_have_an_export_format() {+ assert_eq!(+ texture_export_format(GL_RGBA, GL_UNSIGNED_BYTE),+ Some(ExportFormat::RGBA8888)+ );+ assert_eq!(+ texture_export_format(GL_RGB, GL_UNSIGNED_SHORT_5_6_5),+ Some(ExportFormat::RGB565)+ );+ assert_eq!(+ texture_export_format(GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE),+ Some(ExportFormat::LuminanceAlpha88)+ );+ assert_eq!(texture_export_format(GL_RGB, GL_UNSIGNED_SHORT_4_4_4_4), None);+ assert_eq!(texture_export_format(GL_ALPHA, GL_UNSIGNED_SHORT_5_6_5), None);+ }+}diff --git a/Libraries/LibCompositing/Rust/src/webgl/wire.rs b/Libraries/LibCompositing/Rust/src/webgl/wire.rsindex cf93951a794..5b1c353adc9 100644--- a/Libraries/LibCompositing/Rust/src/webgl/wire.rs+++ b/Libraries/LibCompositing/Rust/src/webgl/wire.rs@@ -52,15 +52,28 @@ const fn offset_of_data_following_struct(struct_size: usize) -> u32 {/// # Safety////// The type is `repr(C)`, made of numbers, booleans and [`DataSpan`]s, and has no byte that is not part of a field.+/// `BOOL_FIELD_OFFSETS` lists where its booleans are.pub unsafe trait WireStruct: Copy + 'static {/// A struct is built from it, so that the bytes that the C ABI leaves unused between its fields, which are fields/// of their own here, do not have to be named.const ZEROED: Self;+ const BOOL_FIELD_OFFSETS: &'static [usize] = &[];fn as_bytes(&self) -> &[u8] {// SAFETY: Per the contract of the trait every byte of the struct is initialized.unsafe { ak::slice_from_raw_parts(ptr::from_ref(self).cast::<u8>(), size_of::<Self>()) }}++ /// The struct that a payload starts with. None where the payload is shorter than the struct, or where it has+ /// another byte than 0 or 1 for a boolean.+ fn read_from(payload: &[u8]) -> Option<Self> {+ if payload.len() < size_of::<Self>() || Self::BOOL_FIELD_OFFSETS.iter().any(|&offset| payload[offset] > 1) {+ return None;+ }+ // SAFETY: The bytes are as many as the struct has, and per the contract of the trait and the check above they+ // are a value of it.+ Some(unsafe { ptr::read_unaligned(payload.as_ptr().cast::<Self>()) })+ }}pub trait Command: WireStruct {@@ -279,6 +292,80 @@ pub fn encode_sync_request<R: SyncRequest>(true}+fn read_header(bytes: &[u8]) -> Option<(u16, usize)> {+ let header: &[u8; HEADER_SIZE] = bytes.first_chunk()?;+ let type_number = u16::from_ne_bytes([header[0], header[1]]);+ let size_after_header = u32::from_ne_bytes(*header[HEADER_PAYLOAD_SIZE_OFFSET..].first_chunk()?);+ Some((type_number, usize::try_from(size_after_header).ok()?))+}++/// The records of a stream of commands, each as its type and its payload.+pub fn records(bytes: &[u8]) -> Records<'_> {+ Records { bytes }+}++pub struct Records<'a> {+ bytes: &'a [u8],+}++impl<'a> Iterator for Records<'a> {+ type Item = Result<(CommandType, &'a [u8]), &'static str>;++ fn next(&mut self) -> Option<Self::Item> {+ if self.bytes.is_empty() {+ return None;+ }+ let bytes = core::mem::take(&mut self.bytes);+ let Some((type_number, payload_size)) = read_header(bytes) else {+ return Some(Err("Truncated WebGL command header"));+ };+ let Some(command_type) = CommandType::from_number(type_number) else {+ return Some(Err("Invalid WebGL command type"));+ };+ let Some((payload, rest)) = bytes[HEADER_SIZE..].split_at_checked(payload_size) else {+ return Some(Err("Truncated WebGL command payload"));+ };+ self.bytes = rest;+ Some(Ok((command_type, payload)))+ }+}++/// The type and the payload of a synchronous request.+pub fn decode_sync_request(bytes: &[u8]) -> Result<(SyncCallType, &[u8]), &'static str> {+ let (type_number, payload_size) = read_header(bytes).ok_or("Truncated WebGL sync call header")?;+ let call_type = SyncCallType::from_number(type_number).ok_or("Invalid WebGL sync call type")?;+ let payload = &bytes[HEADER_SIZE..];+ if payload.len() != payload_size {+ return Err("Truncated WebGL sync call payload");+ }+ Ok((call_type, payload))+}++/// Where the data that follows the struct of a reply is, as [`encode_reply`] lays it out.+pub fn reply_data_spans<R: WireStruct, const N: usize>(sizes: [usize; N]) -> [DataSpan; N] {+ let mut end_of_previous_data = size_of::<R>();+ sizes.map(|size| {+ let offset = end_of_previous_data.next_multiple_of(RECORD_ALIGNMENT);+ end_of_previous_data = offset + size;+ DataSpan {+ offset: u32::try_from(offset).expect("the data of a reply starts in its first 4 GiB"),+ size: u32::try_from(size).expect("the data of a reply is less than 4 GiB"),+ }+ })+}++/// A reply: its struct, and each piece of data that is not empty at the next multiple of the alignment, padded to the+/// alignment as a whole.+pub fn encode_reply<R: WireStruct>(reply: &R, data: &[&[u8]]) -> Vec<u8> {+ let mut bytes = reply.as_bytes().to_vec();+ for data in data.iter().filter(|data| !data.is_empty()) {+ bytes.resize(bytes.len().next_multiple_of(RECORD_ALIGNMENT), 0);+ bytes.extend_from_slice(data);+ }+ bytes.resize(bytes.len().next_multiple_of(RECORD_ALIGNMENT), 0);+ bytes+}+pub fn resolve_data_span(reply: &[u8], span: DataSpan) -> &[u8] {let start = span.offset as usize;start@@ -495,4 +582,109 @@ mod tests {fn a_span_that_leaves_the_reply_is_not_resolved() {resolve_data_span(&[0; 16], DataSpan { offset: 12, size: 5 });}++ #[test]+ fn records_are_read_as_they_are_written() {+ let mut commands = Vec::new();+ let enable = commands::Enable { cap: 7 };+ let data = [1u8, 2, 3];+ let uniform = commands::Uniform1fv {+ location: 9,+ count: 1,+ value: DataSpan::following::<commands::Uniform1fv>(InlineData::Bytes(&data)),+ };+ Record::new(CommandType::Enable, enable.as_bytes(), InlineData::NONE)+ .unwrap()+ .append_to(&mut commands);+ Record::new(CommandType::Uniform1fv, uniform.as_bytes(), InlineData::Bytes(&data))+ .unwrap()+ .append_to(&mut commands);++ let read: Vec<_> = records(&commands).collect::<Result<_, _>>().unwrap();+ assert_eq!(read.len(), 2);+ assert_eq!(read[0].0, CommandType::Enable);+ assert_eq!(commands::Enable::read_from(read[0].1), Some(enable));+ assert_eq!(read[1].0, CommandType::Uniform1fv);+ assert_eq!(commands::Uniform1fv::read_from(read[1].1), Some(uniform));+ assert_eq!(resolve_data_span(read[1].1, uniform.value), data);+ }++ #[test]+ fn a_record_that_the_stream_does_not_hold_is_rejected() {+ assert_eq!(+ records(&header(0, 0)[..7]).next(),+ Some(Err("Truncated WebGL command header"))+ );+ assert_eq!(+ records(&header(u16::MAX, 0)).next(),+ Some(Err("Invalid WebGL command type"))+ );+ let mut truncated = header(CommandType::Enable as u16, 8);+ truncated.extend_from_slice(&[0; 7]);+ let mut read = records(&truncated);+ assert_eq!(read.next(), Some(Err("Truncated WebGL command payload")));+ assert_eq!(read.next(), None);+ }++ #[test]+ fn a_struct_is_read_only_with_booleans_that_are_true_or_false() {+ let command = commands::BufferData {+ has_data: true,+ ..commands::BufferData::ZEROED+ };+ let mut bytes = command.as_bytes().to_vec();+ assert_eq!(commands::BufferData::BOOL_FIELD_OFFSETS, [16]);+ assert_eq!(commands::BufferData::read_from(&bytes), Some(command));+ bytes[16] = 2;+ assert_eq!(commands::BufferData::read_from(&bytes), None);+ assert_eq!(commands::BufferData::read_from(&bytes[..31]), None);+ }++ #[test]+ fn a_request_is_read_as_it_is_written() {+ let name = InlineData::NulTerminated(b"color");+ let request = sync_calls::GetAttribLocationRequest {+ program: 3,+ name: DataSpan::following::<sync_calls::GetAttribLocationRequest>(name),+ };+ let mut request_bytes = Vec::new();+ assert!(encode_sync_request(&mut request_bytes, &request, name));+ let (call_type, payload) = decode_sync_request(&request_bytes).unwrap();+ assert_eq!(call_type, SyncCallType::GetAttribLocation);+ assert_eq!(sync_calls::GetAttribLocationRequest::read_from(payload), Some(request));+ assert_eq!(resolve_data_span(payload, request.name), b"color\0");++ request_bytes.push(0);+ assert_eq!(+ decode_sync_request(&request_bytes),+ Err("Truncated WebGL sync call payload")+ );+ assert_eq!(+ decode_sync_request(&header(u16::MAX, 0)),+ Err("Invalid WebGL sync call type")+ );+ }++ #[test]+ fn a_reply_holds_its_data_where_its_spans_say() {+ let info_log = b"abc";+ let [span] = reply_data_spans::<sync_calls::GetShaderInfoLogReply, 1>([info_log.len()]);+ assert_eq!(span, DataSpan { offset: 16, size: 3 });+ let reply = sync_calls::GetShaderInfoLogReply {+ length: 3,+ info_log: span,+ };+ let bytes = encode_reply(&reply, &[info_log]);+ assert_eq!(bytes.len(), 32);+ assert_eq!(sync_calls::GetShaderInfoLogReply::from_reply_bytes(&bytes), reply);+ assert_eq!(resolve_data_span(&bytes, span), info_log);+ assert_eq!(bytes[19..], [0; 13]);++ let [empty, second] = reply_data_spans::<sync_calls::GetShaderInfoLogReply, 2>([0, 5]);+ assert_eq!(empty, DataSpan { offset: 16, size: 0 });+ assert_eq!(second, DataSpan { offset: 16, size: 5 });+ let bytes = encode_reply(&reply, &[b"", b"hello"]);+ assert_eq!(resolve_data_span(&bytes, second), b"hello");+ assert_eq!(encode_reply(&sync_calls::GetErrorReply::ZEROED, &[]).len(), 16);+ }}diff --git a/Libraries/LibCompositing/WebGL/GLFunctions.json b/Libraries/LibCompositing/WebGL/GLFunctions.jsonindex a660fa5bac6..569c8844ca0 100644--- a/Libraries/LibCompositing/WebGL/GLFunctions.json+++ b/Libraries/LibCompositing/WebGL/GLFunctions.json@@ -2010,6 +2010,21 @@"args": [],"category": "sync"},+ {+ "name": "glGetFloatv",+ "return": "void",+ "args": [+ {+ "type": "GLenum",+ "name": "pname"+ },+ {+ "type": "GLfloat*",+ "name": "data"+ }+ ],+ "category": "custom"+ },{"name": "glGetFloatvRobustANGLE","return": "void",@@ -2062,6 +2077,21 @@],"category": "sync"},+ {+ "name": "glGetIntegerv",+ "return": "void",+ "args": [+ {+ "type": "GLenum",+ "name": "pname"+ },+ {+ "type": "GLint*",+ "name": "data"+ }+ ],+ "category": "custom"+ },{"name": "glGetIntegervRobustANGLE","return": "void",diff --git a/Libraries/LibWeb/Bindings/Rust/generate/webgl_proxy.rs b/Libraries/LibWeb/Bindings/Rust/generate/webgl_proxy.rsindex 6fdd6269872..8ab655eea26 100644--- a/Libraries/LibWeb/Bindings/Rust/generate/webgl_proxy.rs+++ b/Libraries/LibWeb/Bindings/Rust/generate/webgl_proxy.rs@@ -12,8 +12,8 @@use std::fmt::Write;use crate::webgl_wire_model::{- Argument, Category, FieldSpec, Function, WireStruct, WireType, rust_identifier, title_case_to_snake_case,- wire_struct,+ Argument, Category, FieldSpec, Function, PayloadFactor, WireStruct, WireType, rust_identifier,+ title_case_to_snake_case, wire_struct,};fn parameter_name(argument: &Argument) -> String {@@ -40,37 +40,29 @@ fn scalar_parameter_type(function: &Function, argument: &Argument) -> Result<&'s}}-fn size_of_gl_type(gl_type: &str) -> Option<usize> {- Some(match gl_type {- "GLchar" | "GLboolean" => 1,- "GLint" | "GLuint" | "GLfloat" | "GLenum" => 4,- "GLint64" => 8,- _ => return None,- })-}-fn payload_size_expression(function: &Function, argument: &Argument) -> Result<String, String> {- let payload = argument.payload.as_deref().expect("the argument has a payload");let mut factors = Vec::new();- for factor in payload.split(" * ") {- if factor.bytes().all(|byte| byte.is_ascii_digit()) {- factors.push(factor.to_string());- } else if let Some(gl_type) = factor.strip_prefix("sizeof(").and_then(|rest| rest.strip_suffix(')')) {- let size = size_of_gl_type(gl_type)- .ok_or_else(|| unsupported(function, argument, &format!("is counted in {gl_type}")))?;- factors.push(size.to_string());- } else if factor == "(buffer == GL_COLOR ? 4 : 1)" {- factors.push("if buffer == GL_COLOR { 4 } else { 1 }".to_string());- } else {- let counted_by = function- .arguments- .iter()- .find(|other| other.name == factor && !other.is_out);- let name = counted_by.map(parameter_name);- match (name, counted_by.and_then(|other| WireType::of(&other.cpp_type))) {- (Some(name), Some(WireType::I32)) => factors.push(format!("i64::from({name})")),- (Some(name), Some(WireType::I64)) => factors.push(name),- _ => return Err(unsupported(function, argument, &format!("has the size {payload:?}"))),+ for factor in function.payload_size(argument)? {+ match factor {+ PayloadFactor::Constant(constant) => factors.push(constant.to_string()),+ PayloadFactor::ColorBufferComponents(index) => factors.push(format!(+ "if {} == GL_COLOR {{ 4 }} else {{ 1 }}",+ parameter_name(&function.arguments[index])+ )),+ PayloadFactor::Argument(index) => {+ let counted_by = &function.arguments[index];+ let name = parameter_name(counted_by);+ match WireType::of(&counted_by.cpp_type) {+ Some(WireType::I32) => factors.push(format!("i64::from({name})")),+ Some(WireType::I64) => factors.push(name),+ _ => {+ return Err(unsupported(+ function,+ argument,+ &format!("is counted by {}", counted_by.name),+ ));+ }+ }}}}@@ -524,7 +516,7 @@ mod tests {r#"{"name": "glSized", "return": "void", "category": "command", "args": [{"type": "GLint const*", "name": "a", "payload": "strlen(a)"}]}"#,);- assert!(unknown_size.unwrap_err().contains("has the size \"strlen(a)\""));+ assert!(unknown_size.unwrap_err().contains("the size \"strlen(a)\""));let unknown_element = proxy_for(r#"{"name": "glGetDoubles", "return": "void", "category": "sync", "args": [{"type": "GLsizei", "name": "n"},diff --git a/Services/Compositor/Rust/Cargo.toml b/Services/Compositor/Rust/Cargo.tomlindex 8ba0491a27c..51fc819e884 100644--- a/Services/Compositor/Rust/Cargo.toml+++ b/Services/Compositor/Rust/Cargo.toml@@ -21,6 +21,7 @@ rustc-demangle = "0.1"[build-dependencies]cbindgen = "0.29"+serde_json = { version = "1", features = ["float_roundtrip", "preserve_order"] }[lints]workspace = truediff --git a/Services/Compositor/Rust/build.rs b/Services/Compositor/Rust/build.rsindex 11b280a54cb..d4950f2ad94 100644--- a/Services/Compositor/Rust/build.rs+++ b/Services/Compositor/Rust/build.rs@@ -6,12 +6,46 @@use std::env;use std::error::Error;-use std::path::PathBuf;+use std::path::{Path, PathBuf};++#[allow(dead_code, reason = "the model is for the generators of the other crates as well")]+#[path = "../../../Libraries/LibCompositing/Rust/generate/webgl_wire_model.rs"]+mod webgl_wire_model;++#[path = "generate/webgl_replayer.rs"]+mod webgl_replayer;++/// The GL functions that the replayer of WebGL calls, which src/webgl/gl.rs includes, and the methods of the replayer,+/// which src/webgl/replay.rs includes.+fn generate_webgl_replayer(manifest_dir: &Path, out_dir: &Path) -> Result<(), Box<dyn Error>> {+ let libraries = manifest_dir.join("../../../Libraries");+ let functions_path = libraries.join("LibCompositing/WebGL/GLFunctions.json");+ println!("cargo:rerun-if-changed={}", functions_path.display());+ println!(+ "cargo:rerun-if-changed={}",+ libraries.join("LibCompositing/Rust/generate").display()+ );+ println!("cargo:rerun-if-changed=generate");+ let json = std::fs::read_to_string(&functions_path)?;+ let generate = |json: &str| -> Result<(String, String), String> {+ let functions = webgl_wire_model::parse_functions(json)?;+ Ok((+ webgl_replayer::write_gl_functions(&functions)?,+ webgl_replayer::write_replayer(&functions)?,+ ))+ };+ let (gl_functions, replayer) = generate(&json).map_err(|error| format!("{}: {error}", functions_path.display()))?;+ std::fs::write(out_dir.join("webgl_gl.rs"), gl_functions)?;+ std::fs::write(out_dir.join("webgl_replayer.rs"), replayer)?;+ Ok(())+}fn main() -> Result<(), Box<dyn Error>> {let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR")?);let out_dir = PathBuf::from(env::var("OUT_DIR")?);+ generate_webgl_replayer(&manifest_dir, &out_dir)?;+println!("cargo:rerun-if-changed=build.rs");println!("cargo:rerun-if-changed=cbindgen.toml");diff --git a/Services/Compositor/Rust/generate/webgl_replayer.rs b/Services/Compositor/Rust/generate/webgl_replayer.rsnew file mode 100644index 00000000000..03f633cd18f--- /dev/null+++ b/Services/Compositor/Rust/generate/webgl_replayer.rs@@ -0,0 +1,648 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Writes the replaying side of the WebGL command stream from GLFunctions.json: the table of the GL functions that+//! the Compositor calls, which src/webgl/gl.rs includes, and a method of the replayer for every command and every+//! synchronous call that follows from the signature of its GL function, which src/webgl/generated.rs includes.++use std::fmt::Write;++use crate::webgl_wire_model::{+ Argument, Category, DefaultObject, Function, PayloadFactor, WireType, rust_identifier, title_case_to_snake_case,+ wire_struct,+};++fn unsupported(function: &Function, what: &str) -> String {+ format!("the replayer cannot replay {}: {what}", function.name)+}++/// The Rust type of a GL type in the signature of a GL function.+fn gl_rust_type(cpp_type: &str) -> Option<&'static str> {+ Some(match cpp_type {+ "void" => "()",+ "GLenum" | "GLuint" | "GLbitfield" => "u32",+ "GLint" | "GLsizei" => "i32",+ "GLfloat" => "f32",+ "GLboolean" => "u8",+ "GLintptr" | "GLsizeiptr" => "isize",+ "GLuint64" => "u64",+ "GLint64" => "i64",+ "GLsync" | "void*" => "*mut c_void",+ "void const*" => "*const c_void",+ "void**" => "*mut *mut c_void",+ "GLubyte const*" => "*const u8",+ "GLchar const*" => "*const c_char",+ "GLchar*" => "*mut c_char",+ "GLchar const* const*" => "*const *const c_char",+ "GLfloat const*" => "*const f32",+ "GLfloat*" => "*mut f32",+ "GLint const*" => "*const i32",+ "GLint*" | "GLsizei*" => "*mut i32",+ "GLuint const*" | "GLenum const*" => "*const u32",+ "GLuint*" | "GLenum*" => "*mut u32",+ "GLboolean*" => "*mut u8",+ "GLint64*" => "*mut i64",+ _ => return None,+ })+}++fn field_name(argument: &Argument) -> String {+ rust_identifier(&title_case_to_snake_case(&argument.name))+}++/// A scalar argument as GL takes it, from the field of the struct that carries it.+fn scalar_argument(argument: &Argument, holder: &str) -> String {+ let field = field_name(argument);+ if matches!(argument.cpp_type.as_str(), "GLintptr" | "GLsizeiptr") {+ format!("{holder}.{field} as isize")+ } else {+ format!("{holder}.{field}")+ }+}++fn has_gl_signature(function: &Function) -> bool {+ function.category != Category::BuiltinCommand+}++fn parameter_types(function: &Function) -> Result<Vec<&'static str>, String> {+ function+ .arguments+ .iter()+ .map(|argument| {+ gl_rust_type(&argument.cpp_type).ok_or_else(|| {+ unsupported(+ function,+ &format!("{} has the type {}", argument.name, argument.cpp_type),+ )+ })+ })+ .collect()+}++fn return_type(function: &Function) -> Result<&'static str, String> {+ let cpp_type = function.return_type.as_deref().unwrap_or("void");+ gl_rust_type(cpp_type).ok_or_else(|| unsupported(function, &format!("it returns {cpp_type}")))+}++fn function_pointer_type(function: &Function) -> Result<String, String> {+ let parameters = parameter_types(function)?.join(", ");+ let return_type = return_type(function)?;+ Ok(if return_type == "()" {+ format!("unsafe extern \"system\" fn({parameters})")+ } else {+ format!("unsafe extern \"system\" fn({parameters}) -> {return_type}")+ })+}++fn zero_of(rust_type: &str) -> &'static str {+ match rust_type {+ "()" => "()",+ "f32" => "0.0",+ "c_char" | "u8" | "u32" | "i32" | "isize" | "u64" | "i64" => "0",+ _ if rust_type.starts_with("*mut") => "core::ptr::null_mut()",+ _ => "core::ptr::null()",+ }+}++/// The table of GL functions, with a loader, and the functions that the tests of the crate replay against, which+/// record what is called.+pub fn write_gl_functions(functions: &[Function]) -> Result<String, String> {+ let functions: Vec<&Function> = functions.iter().filter(|function| has_gl_signature(function)).collect();+ let mut out = String::from("// Generated by build.rs from Libraries/LibCompositing/WebGL/GLFunctions.json.\n\n");+ out.push_str("use core::ffi::{CStr, c_char, c_void};\n\n");++ out.push_str("/// The GL functions that the replayer calls.\npub struct GlFunctions {\n");+ for function in &functions {+ writeln!(+ out,+ " pub {}: {},",+ function.method_name(),+ function_pointer_type(function)?+ )+ .unwrap();+ }+ out.push_str("}\n\n");++ out.push_str(+ "impl GlFunctions {\n /// Answers the name of a function that `get_proc_address` does not know.\n ///\n /// # Safety\n ///\n /// `get_proc_address` answers the address of the GL function of a name, or null.\n pub unsafe fn load(mut get_proc_address: impl FnMut(&CStr) -> *const c_void) -> Result<Self, &'static CStr> {\n // SAFETY: Each field has the type of the function of its name.\n unsafe {\n Ok(Self {\n",+ );+ for function in &functions {+ writeln!(+ out,+ " {}: load_function(&mut get_proc_address, c\"{}\")?,",+ function.method_name(),+ function.name+ )+ .unwrap();+ }+ out.push_str(" })\n }\n }\n}\n\n");+ out.push_str(+ "/// # Safety\n///\n/// `F` is the type of a pointer to the GL function of the name.\nunsafe fn load_function<F: Copy>(\n get_proc_address: &mut impl FnMut(&CStr) -> *const c_void,\n name: &'static CStr,\n) -> Result<F, &'static CStr> {\n const { assert!(size_of::<F>() == size_of::<*const c_void>()) };\n let address = get_proc_address(name);\n if address.is_null() {\n return Err(name);\n }\n // SAFETY: The address is that of the function, whose type the caller names.\n Ok(unsafe { core::mem::transmute_copy::<*const c_void, F>(&address) })\n}\n\n",+ );++ out.push_str("#[cfg(test)]\n#[allow(clippy::too_many_arguments)]\npub mod recording {\n");+ out.push_str(" use super::*;\n\n");+ out.push_str(" fn pointer_text<T>(pointer: *const T) -> &'static str {\n if pointer.is_null() { \"null\" } else { \"ptr\" }\n }\n\n");+ for function in &functions {+ let types = parameter_types(function)?;+ let return_type = return_type(function)?;+ let parameters: Vec<String> = function+ .arguments+ .iter()+ .zip(&types)+ .map(|(argument, rust_type)| format!("{}: {rust_type}", field_name(argument)))+ .collect();+ let arguments: Vec<String> = function+ .arguments+ .iter()+ .zip(&types)+ .map(|(argument, rust_type)| {+ let name = field_name(argument);+ if rust_type.starts_with("*mut") {+ format!("pointer_text({name}.cast_const())")+ } else if rust_type.starts_with('*') {+ format!("pointer_text({name})")+ } else {+ format!("&{name}")+ }+ })+ .collect();+ let format_string = vec!["{:?}"; arguments.len()].join(", ");+ let signature_return = if return_type == "()" {+ String::new()+ } else {+ format!(" -> {return_type}")+ };+ writeln!(+ out,+ " pub unsafe extern \"system\" fn {}({}){signature_return} {{",+ function.method_name(),+ parameters.join(", ")+ )+ .unwrap();+ writeln!(+ out,+ " crate::webgl::testing::record(format!(\"{}({format_string})\"{}));",+ function.name,+ arguments+ .iter()+ .map(|argument| format!(", {argument}"))+ .collect::<String>()+ )+ .unwrap();+ let is_gen = function.category == Category::Gen;+ if is_gen && function.returns_void() {+ let count = field_name(&function.arguments[0]);+ let names = field_name(&function.arguments[1]);+ writeln!(+ out,+ " for index in 0..usize::try_from({count}).unwrap_or(0) {{\n // SAFETY: The replayer passes room for as many names.\n unsafe {{ {names}.add(index).write(crate::webgl::testing::next_name()) }};\n }}"+ )+ .unwrap();+ } else if is_gen && return_type == "u32" {+ out.push_str(" crate::webgl::testing::next_name()\n");+ } else if is_gen {+ out.push_str(" crate::webgl::testing::next_name() as usize as *mut c_void\n");+ } else if return_type != "()" {+ writeln!(out, " {}", zero_of(return_type)).unwrap();+ }+ out.push_str(" }\n\n");+ }+ out.push_str(" pub fn functions() -> GlFunctions {\n GlFunctions {\n");+ for function in &functions {+ writeln!(+ out,+ " {}: {},",+ function.method_name(),+ function.method_name()+ )+ .unwrap();+ }+ out.push_str(" }\n }\n}\n");+ Ok(out)+}++fn wire_type_of(function: &Function, argument: &Argument) -> Result<WireType, String> {+ WireType::of(&argument.cpp_type)+ .ok_or_else(|| unsupported(function, &format!("{} has no wire type", argument.name)))+}++/// The factors of the size that the JSON gives for the data of an argument, as `i64` expressions of the fields of+/// `holder`.+fn size_factors(function: &Function, argument: &Argument, holder: &str) -> Result<String, String> {+ let mut factors = Vec::new();+ for factor in function.payload_size(argument)? {+ factors.push(match factor {+ PayloadFactor::Constant(constant) => format!("{constant}_i64"),+ PayloadFactor::Argument(index) => {+ let counted_by = &function.arguments[index];+ let field = format!("{holder}.{}", field_name(counted_by));+ match wire_type_of(function, counted_by)? {+ WireType::I64 => field,+ WireType::I32 | WireType::U32 => format!("i64::from({field})"),+ _ => {+ return Err(unsupported(+ function,+ &format!("{} counts with {}", argument.name, counted_by.name),+ ));+ }+ }+ }+ PayloadFactor::ColorBufferComponents(index) => format!(+ "if {holder}.{} == GL_COLOR {{ 4 }} else {{ 1 }}",+ field_name(&function.arguments[index])+ ),+ });+ }+ Ok(format!("&[{}]", factors.join(", ")))+}++fn element_type(argument: &Argument) -> Option<&'static str> {+ let pointee = argument.pointee_cpp_type().replace("const", "");+ match pointee.trim() {+ "void" | "GLchar" => None,+ "GLfloat" => Some("f32"),+ "GLint" | "GLsizei" => Some("i32"),+ "GLuint" | "GLenum" => Some("u32"),+ "GLboolean" => Some("u8"),+ "GLint64" => Some("i64"),+ _ => None,+ }+}++fn data_pointer(argument: &Argument, bytes: &str) -> String {+ match element_type(argument) {+ Some(element) => format!("typed_data::<{element}>({bytes})?"),+ None => format!("{bytes}.as_ptr().cast()"),+ }+}++/// Resolves the data of an argument that points at some, and answers what the GL function is passed for it.+fn write_data_resolution(out: &mut String, function: &Function, argument: &Argument) -> Result<String, String> {+ let field = field_name(argument);+ let name = function.command_name();+ let mismatch = format!(+ "ReplayError(\"the data of {name}.{} has another size than its arguments give\")",+ argument.name+ );+ let factors = size_factors(function, argument, "command")?;+ if argument.is_nullable {+ writeln!(+ out,+ " let {field}_data = if command.has_{field} {{+ let bytes = if command.{field}.size != 0 {{ data_span(payload, command.{field})? }} else {{ &[] }};+ if !size_matches(bytes.len(), {factors}) {{+ return Err({mismatch});+ }}+ if command.{field}.size != 0 {{ {} }} else {{ core::ptr::null() }}+ }} else {{+ if command.{field}.size != 0 {{+ return Err(ReplayError(\"{name}.{} has data although it has none\"));+ }}+ core::ptr::null()+ }};",+ data_pointer(argument, "bytes"),+ argument.name+ )+ .unwrap();+ } else {+ writeln!(+ out,+ " let {field}_bytes = data_span(payload, command.{field})?;+ if !size_matches({field}_bytes.len(), {factors}) {{+ return Err({mismatch});+ }}+ let {field}_data = {};",+ data_pointer(argument, &format!("{field}_bytes"))+ )+ .unwrap();+ }+ Ok(format!("{field}_data"))+}++fn write_command(out: &mut String, function: &Function) -> Result<(), String> {+ let name = function.command_name();+ writeln!(+ out,+ " fn replay_{}(&mut self, payload: &[u8]) -> Result<(), ReplayError> {{",+ function.method_name()+ )+ .unwrap();+ if function.arguments.is_empty() {+ writeln!(out, " decode::<commands::{name}>(payload)?;").unwrap();+ } else {+ writeln!(out, " let command: commands::{name} = decode(payload)?;").unwrap();+ }+ let mut arguments = Vec::new();+ for argument in &function.arguments {+ let field = field_name(argument);+ let take_or_lookup = if function.deletes_objects { "take" } else { "lookup" };+ if argument.is_string {+ writeln!(+ out,+ " let {field}_data = string_data(payload, command.{field})?;"+ )+ .unwrap();+ arguments.push(format!("{field}_data"));+ } else if argument.is_offset {+ arguments.push(format!("command.{field} as isize as *const c_void"));+ } else if argument.is_object && !argument.is_pointer() {+ if argument.cpp_type == "GLsync" {+ writeln!(+ out,+ " let {field} = self.objects.{take_or_lookup}_sync(command.{field});"+ )+ .unwrap();+ } else if let Some(default) = argument.zero_means_default {+ let default = match default {+ DefaultObject::Framebuffer => "framebuffer",+ DefaultObject::Renderbuffer => "renderbuffer",+ };+ writeln!(+ out,+ " let {field} = if command.{field} == 0 {{ self.defaults.{default} }} else {{ self.objects.lookup(command.{field}) }};"+ )+ .unwrap();+ } else {+ writeln!(+ out,+ " let {field} = self.objects.{take_or_lookup}(command.{field});"+ )+ .unwrap();+ }+ arguments.push(field);+ } else if argument.is_object && argument.is_const_pointer() {+ let factors = size_factors(function, argument, "command")?;+ writeln!(+ out,+ " let {field}_bytes = data_span(payload, command.{field})?;+ if !size_matches({field}_bytes.len(), {factors}) {{+ return Err(ReplayError(\"the objects of {name}.{} have another size than its arguments give\"));+ }}+ let {field}: Vec<u32> = object_ids({field}_bytes)?.map(|id| self.objects.{take_or_lookup}(id)).collect();",+ argument.name+ )+ .unwrap();+ arguments.push(format!("{field}.as_ptr()"));+ } else if argument.payload.is_some() {+ arguments.push(write_data_resolution(out, function, argument)?);+ } else if argument.is_pointer() {+ return Err(unsupported(+ function,+ &format!("{} points at what has no size", argument.name),+ ));+ } else {+ arguments.push(scalar_argument(argument, "command"));+ }+ }+ writeln!(+ out,+ " // SAFETY: The context of the replayer is current, and every pointer is valid for what GL reads of it.\n unsafe {{ (self.gl.{})({}) }};\n Ok(())\n }}\n",+ function.method_name(),+ arguments.join(", ")+ )+ .unwrap();+ Ok(())+}++fn write_gen(out: &mut String, function: &Function) {+ let name = function.command_name();+ let method = function.method_name();+ writeln!(+ out,+ " fn replay_{method}(&mut self, payload: &[u8]) -> Result<(), ReplayError> {{\n let command: commands::{name} = decode(payload)?;"+ )+ .unwrap();+ if function.returns_void() {+ let count = field_name(&function.arguments[0]);+ let ids = field_name(&function.arguments[1]);+ writeln!(+ out,+ " let ids = object_ids(data_span(payload, command.{ids})?)?;+ if i64::try_from(ids.len()) != Ok(i64::from(command.{count})) {{+ return Err(ReplayError(\"{name} has another number of objects than it creates\"));+ }}+ for id in ids {{+ let mut name = 0;+ // SAFETY: The context of the replayer is current, and the name is room for one.+ unsafe {{ (self.gl.{method})(1, &raw mut name) }};+ self.objects.add(id, name)?;+ }}+ Ok(())+ }}+"+ )+ .unwrap();+ return;+ }+ let arguments: Vec<String> = function+ .arguments+ .iter()+ .map(|argument| scalar_argument(argument, "command"))+ .collect();+ let add = if function.return_type.as_deref() == Some("GLsync") {+ "add_sync"+ } else {+ "add"+ };+ writeln!(+ out,+ " // SAFETY: The context of the replayer is current.\n let object = unsafe {{ (self.gl.{method})({}) }};\n self.objects.{add}(command.id, object)?;\n Ok(())\n }}\n",+ arguments.join(", ")+ )+ .unwrap();+}++fn write_sync_call(out: &mut String, function: &Function) -> Result<(), String> {+ let name = function.command_name();+ let method = function.method_name();+ writeln!(+ out,+ " fn handle_{method}(&mut self, payload: &[u8]) -> Result<Vec<u8>, ReplayError> {{"+ )+ .unwrap();+ if function.arguments.iter().any(|argument| !argument.is_out) {+ writeln!(+ out,+ " let request: sync_calls::{name}Request = decode(payload)?;"+ )+ .unwrap();+ } else {+ writeln!(out, " let _: sync_calls::{name}Request = decode(payload)?;").unwrap();+ }+ let mut arguments = Vec::new();+ let mut blobs = Vec::new();+ let mut reply_fields = Vec::new();+ for argument in &function.arguments {+ let field = field_name(argument);+ if let Some(value) = &argument.host_override {+ arguments.push(value.clone());+ } else if argument.is_out {+ if argument.payload.is_some() {+ let element = gl_rust_type(&argument.cpp_type)+ .and_then(|pointer| pointer.strip_prefix("*mut "))+ .ok_or_else(|| unsupported(function, &format!("{} is no buffer", argument.name)))?;+ let factors = size_factors(function, argument, "request")?;+ writeln!(+ out,+ " let mut {field} = vec![{}; out_data_size({factors})? / size_of::<{element}>()];",+ zero_of(element)+ )+ .unwrap();+ arguments.push(format!("{field}.as_mut_ptr()"));+ blobs.push((field.clone(), element));+ reply_fields.push(format!("{field}: spans[{}]", blobs.len() - 1));+ } else {+ let element = gl_rust_type(&argument.pointee_cpp_type())+ .ok_or_else(|| unsupported(function, &format!("{} has no value type", argument.name)))?;+ writeln!(out, " let mut {field}: {element} = {};", zero_of(element)).unwrap();+ arguments.push(format!("&raw mut {field}"));+ reply_fields.push(field);+ }+ } else if argument.is_object && !argument.is_pointer() {+ let lookup = if argument.cpp_type == "GLsync" {+ "lookup_sync"+ } else {+ "lookup"+ };+ writeln!(out, " let {field} = self.objects.{lookup}(request.{field});").unwrap();+ arguments.push(field);+ } else if argument.is_string {+ writeln!(+ out,+ " let {field}_data = string_data(payload, request.{field})?;"+ )+ .unwrap();+ arguments.push(format!("{field}_data"));+ } else if argument.payload.is_some() {+ let factors = size_factors(function, argument, "request")?;+ writeln!(+ out,+ " let {field}_bytes = data_span(payload, request.{field})?;+ if !size_matches({field}_bytes.len(), {factors}) {{+ return Err(ReplayError(\"the data of {name}.{} has another size than its arguments give\"));+ }}",+ argument.name+ )+ .unwrap();+ arguments.push(data_pointer(argument, &format!("{field}_bytes")));+ } else if argument.is_pointer() {+ return Err(unsupported(+ function,+ &format!("{} points at what has no size", argument.name),+ ));+ } else {+ arguments.push(scalar_argument(argument, "request"));+ }+ }++ let invocation = if function.name == "glGetError" {+ "self.get_error()".to_string()+ } else {+ out.push_str(+ " // SAFETY: The context of the replayer is current, and every pointer is valid for what GL reads and\n // writes of it.\n",+ );+ format!("unsafe {{ (self.gl.{method})({}) }}", arguments.join(", "))+ };+ if function.returns_void() {+ writeln!(out, " {invocation};").unwrap();+ } else {+ writeln!(out, " let return_value = {invocation};").unwrap();+ reply_fields.insert(0, "return_value".into());+ }++ if !blobs.is_empty() {+ let blob_sizes: Vec<String> = blobs+ .iter()+ .map(|(field, element)| format!("{field}.len() * size_of::<{element}>()"))+ .collect();+ writeln!(+ out,+ " let spans = reply_data_spans::<sync_calls::{name}Reply, {}>([{}]);",+ blobs.len(),+ blob_sizes.join(", ")+ )+ .unwrap();+ }+ let reply_layout = wire_struct(format!("SyncCalls::{name}::Reply"), function.sync_reply_fields())?;+ let rest_of_reply = if reply_layout.has_unused_bytes() {+ format!("..sync_calls::{name}Reply::ZEROED")+ } else {+ String::new()+ };+ writeln!(+ out,+ " let reply = sync_calls::{name}Reply {{ {}{rest_of_reply} }};",+ reply_fields.join(", ")+ + if reply_fields.is_empty() || rest_of_reply.is_empty() {+ ""+ } else {+ ", "+ }+ )+ .unwrap();+ let blob_bytes: Vec<String> = blobs+ .iter()+ .map(|(field, _)| format!("bytes_of_slice(&{field})"))+ .collect();+ writeln!(+ out,+ " Ok(encode_reply(&reply, &[{}]))\n }}\n",+ blob_bytes.join(", ")+ )+ .unwrap();+ Ok(())+}++/// The methods of the replayer that follow from the signatures of GL functions, and the dispatch of every command+/// and every synchronous call to its method. The others are written by hand, under the name of their function.+pub fn write_replayer(functions: &[Function]) -> Result<String, String> {+ let mut out = String::from("// Generated by build.rs from Libraries/LibCompositing/WebGL/GLFunctions.json.\n\n");+ out.push_str("impl<H: WebGLHost> Replayer<'_, H> {\n");++ out.push_str(+ " pub fn replay_record(&mut self, command_type: CommandType, payload: &[u8]) -> Result<(), ReplayError> {\n match command_type {\n",+ );+ for function in functions.iter().filter(|function| function.is_command_stream_entry()) {+ let name = function.command_name();+ let method = function.method_name();+ if matches!(function.category, Category::Command | Category::Gen) {+ writeln!(out, " CommandType::{name} => self.replay_{method}(payload),").unwrap();+ } else {+ writeln!(out, " CommandType::{name} => self.{method}(payload),").unwrap();+ }+ }+ out.push_str(" }\n }\n\n");++ out.push_str(+ " pub fn handle_sync_call(&mut self, call_type: SyncCallType, payload: &[u8]) -> Result<Vec<u8>, ReplayError> {\n match call_type {\n",+ );+ for function in functions.iter().filter(|function| function.is_sync_call()) {+ let name = function.command_name();+ let method = function.method_name();+ if function.category == Category::Sync {+ writeln!(+ out,+ " SyncCallType::{name} => self.handle_{method}(payload),"+ )+ .unwrap();+ } else {+ writeln!(out, " SyncCallType::{name} => self.{method}(payload),").unwrap();+ }+ }+ out.push_str(" }\n }\n\n");++ for function in functions {+ match function.category {+ Category::Command => write_command(&mut out, function)?,+ Category::Gen => write_gen(&mut out, function),+ Category::Sync => write_sync_call(&mut out, function)?,+ Category::Custom | Category::BuiltinCommand => {}+ }+ }+ out.push_str("}\n");+ Ok(out)+}diff --git a/Services/Compositor/Rust/src/lib.rs b/Services/Compositor/Rust/src/lib.rsindex c271a11e9a3..73fac65d577 100644--- a/Services/Compositor/Rust/src/lib.rs+++ b/Services/Compositor/Rust/src/lib.rs@@ -38,6 +38,7 @@ pub mod scroll_fling_controller;pub mod scroll_snap_controller;pub mod scrollbar_controller;pub mod surfaces;+pub mod webgl;pub mod wheel_gesture_routing;#[cfg(test)]diff --git a/Services/Compositor/Rust/src/webgl/custom.rs b/Services/Compositor/Rust/src/webgl/custom.rsnew file mode 100644index 00000000000..5a02176d055--- /dev/null+++ b/Services/Compositor/Rust/src/webgl/custom.rs@@ -0,0 +1,670 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The commands and the synchronous calls whose structs GLFunctions.json spells out, which the replayer handles by+//! hand: those of the strings that GL takes as arrays, of the drawing buffer, and of the images that a texture upload+//! takes its pixels from.++use core::ffi::{CStr, c_char, c_void};++use libcompositing_rust::webgl::ImageSource;+use libcompositing_rust::webgl::texture_upload::texture_export_format;+use libcompositing_rust::webgl::vocabulary::{commands, sync_calls};+use libcompositing_rust::webgl::wire::{encode_reply, reply_data_spans};+use libgfx_rust::IntSize;++use super::gl::GlFunctions;+use super::gl_constants::*;+use super::host::{DefaultBuffers, ImageConversion, ImageConversionOutcome, VideoFrameCopy, WebGLHost};+use super::replay::{ReplayError, Replayer, bytes_of_slice, data_span, decode, split_packed_strings, string_data};++const MAX_DRAWING_BUFFER_DIMENSION: i32 = 16384;++fn copy_can_write_internal_format(internalformat: i32) -> bool {+ u32::try_from(internalformat).is_ok_and(|internalformat| {+ matches!(+ internalformat,+ GL_ALPHA+ | GL_LUMINANCE+ | GL_LUMINANCE_ALPHA+ | GL_RGB+ | GL_RGBA+ | GL_SRGB_EXT+ | GL_SRGB_ALPHA_EXT+ | GL_R8+ | GL_RG8+ | GL_RGB8+ | GL_RGBA8+ | GL_SRGB8+ | GL_SRGB8_ALPHA8+ | GL_RGB565+ | GL_RGBA4+ | GL_RGB5_A1+ | GL_RGB10_A2+ | GL_RGB9_E5+ | GL_R11F_G11F_B10F+ | GL_R16F+ | GL_RG16F+ | GL_RGB16F+ | GL_RGBA16F+ | GL_R32F+ | GL_RG32F+ | GL_RGB32F+ | GL_RGBA32F+ )+ })+}++fn format_is_integer(format: u32) -> bool {+ matches!(+ format,+ GL_RED_INTEGER | GL_RG_INTEGER | GL_RGB_INTEGER | GL_RGBA_INTEGER+ )+}++fn upload_size(+ frame_size: IntSize,+ has_explicit_destination_size: bool,+ destination_width: i32,+ destination_height: i32,+) -> Option<IntSize> {+ if !has_explicit_destination_size {+ return Some(frame_size);+ }+ (destination_width >= 0 && destination_height >= 0).then_some(IntSize {+ width: destination_width,+ height: destination_height,+ })+}++/// The extensions that GL has enabled, or that ANGLE can enable on request.+pub fn supported_extensions(gl: &GlFunctions) -> Vec<String> {+ let mut extensions = Vec::new();+ for list in [GL_EXTENSIONS, GL_REQUESTABLE_EXTENSIONS_ANGLE] {+ // SAFETY: A context is current, and GL answers a string or null.+ let names = unsafe { (gl.get_string)(list) };+ if names.is_null() {+ continue;+ }+ // SAFETY: GL answers a NUL-terminated string.+ let names = unsafe { CStr::from_ptr(names.cast()) }.to_string_lossy();+ extensions.extend(names.split(' ').filter(|name| !name.is_empty()).map(String::from));+ }+ extensions+}++fn extension_is_enabled(gl: &GlFunctions, extension: &[u8]) -> bool {+ // SAFETY: A context is current, and GL answers a string or null.+ let names = unsafe { (gl.get_string)(GL_EXTENSIONS) };+ // SAFETY: GL answers a NUL-terminated string.+ !names.is_null()+ && unsafe { CStr::from_ptr(names.cast()) }+ .to_bytes()+ .split(|&byte| byte == b' ')+ .any(|name| name == extension)+}++/// Clears the drawing buffer to the values that WebGL clears it to between frames, and restores the clear values and the+/// bindings of the page.+pub fn clear_buffer_to_default_values(gl: &GlFunctions, webgl2: bool, defaults: DefaultBuffers) {+ let (framebuffer_target, framebuffer_binding) = if webgl2 {+ (GL_DRAW_FRAMEBUFFER, GL_DRAW_FRAMEBUFFER_BINDING)+ } else {+ (GL_FRAMEBUFFER, GL_FRAMEBUFFER_BINDING)+ };+ let mut original_framebuffer = 0;+ let mut original_renderbuffer = 0;+ let mut clear_color = [0.0_f32; 4];+ let mut clear_depth = 0.0_f32;+ let mut clear_stencil = 0;+ // SAFETY: A context is current, and every pointer is room for what GL writes.+ unsafe {+ (gl.get_integerv)(framebuffer_binding, &raw mut original_framebuffer);+ (gl.get_integerv)(GL_RENDERBUFFER_BINDING, &raw mut original_renderbuffer);+ (gl.bind_framebuffer)(framebuffer_target, defaults.framebuffer);+ (gl.bind_renderbuffer)(GL_RENDERBUFFER, defaults.renderbuffer);+ (gl.get_floatv)(GL_COLOR_CLEAR_VALUE, clear_color.as_mut_ptr());+ (gl.get_floatv)(GL_DEPTH_CLEAR_VALUE, &raw mut clear_depth);+ (gl.get_integerv)(GL_STENCIL_CLEAR_VALUE, &raw mut clear_stencil);+ (gl.clear_color)(0.0, 0.0, 0.0, 0.0);+ (gl.clear_depthf)(1.0);+ (gl.clear_stencil)(0);+ (gl.clear)(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);+ (gl.clear_color)(clear_color[0], clear_color[1], clear_color[2], clear_color[3]);+ (gl.clear_depthf)(clear_depth);+ (gl.clear_stencil)(clear_stencil);+ (gl.bind_framebuffer)(framebuffer_target, original_framebuffer as u32);+ (gl.bind_renderbuffer)(GL_RENDERBUFFER, original_renderbuffer as u32);+ }+}++/// The pixels of an image as a texture upload takes them, or the negative size that GL is to reject.+struct ConvertedImage<P> {+ pixels: Option<P>,+ width: i32,+ height: i32,+}++/// What an upload from an image asks for, whatever kind of upload it is.+struct ImageUpload {+ bitmap_index: u32,+ format: u32,+ r#type: u32,+ has_explicit_destination_size: bool,+ destination_width: i32,+ destination_height: i32,+ flip_y: bool,+ premultiply_alpha: bool,+}++macro_rules! image_upload {+ ($command:expr) => {+ ImageUpload {+ bitmap_index: $command.bitmap_index,+ format: $command.format,+ r#type: $command.r#type,+ has_explicit_destination_size: $command.has_explicit_destination_size,+ destination_width: $command.destination_width,+ destination_height: $command.destination_height,+ flip_y: $command.flip_y,+ premultiply_alpha: $command.premultiply_alpha,+ }+ };+}++fn pixels_of<P: AsRef<[u8]>>(image: &ConvertedImage<P>) -> Result<(i32, *const c_void), ReplayError> {+ let bytes = image.pixels.as_ref().map_or(&[][..], AsRef::as_ref);+ let size = i32::try_from(bytes.len()).map_err(|_| ReplayError("WebGL image upload is too big"))?;+ Ok((size, bytes.as_ptr().cast()))+}++impl<H: WebGLHost> Replayer<'_, H> {+ pub(super) fn shader_source(&mut self, payload: &[u8]) -> Result<(), ReplayError> {+ let command: commands::ShaderSource = decode(payload)?;+ let source = string_data(payload, command.source)?;+ let shader = self.objects.lookup(command.shader);+ let length =+ i32::try_from(command.source.size - 1).map_err(|_| ReplayError("WebGL shader source is too long"))?;+ // SAFETY: The context of the replayer is current, and the source has the length.+ unsafe { (self.gl.shader_source)(shader, 1, &raw const source, &raw const length) };+ Ok(())+ }++ pub(super) fn transform_feedback_varyings(&mut self, payload: &[u8]) -> Result<(), ReplayError> {+ let command: commands::TransformFeedbackVaryings = decode(payload)?;+ let varyings = split_packed_strings(data_span(payload, command.varyings)?, command.count)?;+ let program = self.objects.lookup(command.program);+ // SAFETY: The context of the replayer is current, and every string is NUL-terminated.+ unsafe {+ (self.gl.transform_feedback_varyings)(program, command.count, varyings.as_ptr(), command.buffer_mode);+ }+ Ok(())+ }++ pub(super) fn set_drawing_buffer_size(&mut self, payload: &[u8]) -> Result<(), ReplayError> {+ let command: commands::SetDrawingBufferSize = decode(payload)?;+ let dimensions = 1..=MAX_DRAWING_BUFFER_DIMENSION;+ if !dimensions.contains(&command.width) || !dimensions.contains(&command.height) {+ return Err(ReplayError("WebGL drawing buffer size is out of range"));+ }+ let size = IntSize {+ width: command.width,+ height: command.height,+ };+ self.host+ .set_webgl_drawing_buffer_size(self.client, self.canvas_id, size);+ self.defaults = self.host.make_webgl_context_current(self.client, self.canvas_id);+ Ok(())+ }++ pub(super) fn read_pixels_into_pixel_pack_buffer(&mut self, payload: &[u8]) -> Result<(), ReplayError> {+ let command: commands::ReadPixelsIntoPixelPackBuffer = decode(payload)?;+ // SAFETY: The context of the replayer is current, and GL writes into the bound pixel pack buffer at the offset.+ unsafe {+ (self.gl.read_pixels_robust_angle)(+ command.x,+ command.y,+ command.width,+ command.height,+ command.format,+ command.r#type,+ 0,+ core::ptr::null_mut(),+ core::ptr::null_mut(),+ core::ptr::null_mut(),+ command.offset as isize as *mut c_void,+ );+ }+ Ok(())+ }++ fn image_source_at(&self, bitmap_index: u32) -> Result<ImageSource, ReplayError> {+ self.image_sources+ .get(bitmap_index as usize)+ .copied()+ .ok_or(ReplayError("WebGL image upload references an out-of-range bitmap"))+ }++ /// None where the image could not be converted, which leaves the texture as it is.+ fn converted_image(&self, upload: &ImageUpload) -> Result<Option<ConvertedImage<H::Pixels>>, ReplayError> {+ let source = self.image_source_at(upload.bitmap_index)?;+ let export_format = texture_export_format(upload.format, upload.r#type).ok_or(ReplayError(+ "WebGL image upload has an unsupported format and type combination",+ ))?;+ let mut target_size = None;+ if upload.has_explicit_destination_size {+ if upload.destination_width < 0 || upload.destination_height < 0 {+ return Ok(Some(ConvertedImage {+ pixels: None,+ width: upload.destination_width,+ height: upload.destination_height,+ }));+ }+ target_size = Some(IntSize {+ width: upload.destination_width,+ height: upload.destination_height,+ });+ }+ let conversion = ImageConversion {+ export_format,+ flip_y: upload.flip_y,+ premultiply_alpha: upload.premultiply_alpha,+ target_size,+ };+ match self.host.convert_image_source(self.client, source, conversion) {+ ImageConversionOutcome::Converted { pixels, width, height } => Ok(Some(ConvertedImage {+ pixels: Some(pixels),+ width,+ height,+ })),+ ImageConversionOutcome::UnknownImageFrame => Err(ReplayError(+ "WebGL image upload names an image frame that is not registered",+ )),+ ImageConversionOutcome::Failed => {+ eprintln!("Compositor: Could not convert an image for a WebGL texture upload");+ Ok(None)+ }+ }+ }++ fn supports_pixel_buffer_objects(&self) -> bool {+ self.webgl2 || extension_is_enabled(self.gl, b"GL_NV_pixel_buffer_object")+ }++ fn supports_unpack_subimage_parameters(&self) -> bool {+ self.webgl2 || extension_is_enabled(self.gl, b"GL_EXT_unpack_subimage")+ }++ fn with_pixel_unpack_buffer_unbound(&self, upload: impl FnOnce()) {+ let has_pixel_buffer_objects = self.supports_pixel_buffer_objects();+ let mut bound_buffer = 0;+ if has_pixel_buffer_objects {+ // SAFETY: The context of the replayer is current, and the binding is room for one value.+ unsafe {+ (self.gl.get_integerv_robust_angle)(+ GL_PIXEL_UNPACK_BUFFER_BINDING,+ 1,+ core::ptr::null_mut(),+ &raw mut bound_buffer,+ );+ (self.gl.bind_buffer)(GL_PIXEL_UNPACK_BUFFER, 0);+ }+ }+ upload();+ if has_pixel_buffer_objects {+ // SAFETY: The context of the replayer is current.+ unsafe { (self.gl.bind_buffer)(GL_PIXEL_UNPACK_BUFFER, bound_buffer as u32) };+ }+ }++ /// The pixels of a converted image are tightly packed, row after row and image after image, so the unpack+ /// parameters that the page set for its own data are reset for the upload, and restored after it.+ fn with_packed_unpack_state(&self, upload: impl FnOnce()) {+ let mut saved_parameters = Vec::with_capacity(6);+ let mut reset = |parameter: u32, value: i32| {+ let mut saved_value = 0;+ // SAFETY: The context of the replayer is current, and the saved value is room for one value.+ unsafe {+ (self.gl.get_integerv)(parameter, &raw mut saved_value);+ (self.gl.pixel_storei)(parameter, value);+ }+ saved_parameters.push((parameter, saved_value));+ };+ reset(GL_UNPACK_ALIGNMENT, 1);+ if self.supports_unpack_subimage_parameters() {+ reset(GL_UNPACK_ROW_LENGTH, 0);+ reset(GL_UNPACK_SKIP_PIXELS, 0);+ reset(GL_UNPACK_SKIP_ROWS, 0);+ }+ if self.webgl2 {+ reset(GL_UNPACK_IMAGE_HEIGHT, 0);+ reset(GL_UNPACK_SKIP_IMAGES, 0);+ }+ upload();+ for (parameter, saved_value) in saved_parameters {+ // SAFETY: The context of the replayer is current.+ unsafe { (self.gl.pixel_storei)(parameter, saved_value) };+ }+ }++ /// Defines the level of the texture with the call that an upload of pixels would make, so that WebGL sees the same+ /// errors, and copies the frame into it on the GPU. False where the frame has to be uploaded as pixels instead.+ fn define_texture_image_from_video_frame(+ &mut self,+ command: &commands::TexImage2DFromBitmap,+ frame: &H::VideoFrame,+ frame_size: IntSize,+ ) -> bool {+ if !self+ .host+ .webgl_can_copy_images_into_textures(self.client, self.canvas_id)+ || !copy_can_write_internal_format(command.internalformat)+ {+ return false;+ }+ let Some(size) = upload_size(+ frame_size,+ command.has_explicit_destination_size,+ command.destination_width,+ command.destination_height,+ ) else {+ return false;+ };+ let Some(image) = self.host.video_frame_image(frame) else {+ return false;+ };++ self.stash_errors();+ self.with_pixel_unpack_buffer_unbound(|| {+ // SAFETY: The context of the replayer is current, and GL reads no pixels.+ unsafe {+ (self.gl.tex_image2d_robust_angle)(+ command.target,+ command.level,+ command.internalformat,+ size.width,+ size.height,+ 0,+ command.format,+ command.r#type,+ 0,+ core::ptr::null(),+ );+ }+ });+ if self.stash_errors() || size.is_empty() {+ return true;+ }+ let copy = VideoFrameCopy {+ source_size: frame_size,+ size,+ target: command.target,+ level: command.level,+ xoffset: 0,+ yoffset: 0,+ flip_y: command.flip_y,+ premultiply_alpha: command.premultiply_alpha,+ };+ if !self+ .host+ .copy_video_frame_image_into_bound_texture(self.client, self.canvas_id, &image, copy)+ {+ return false;+ }+ self.discard_errors();+ true+ }++ fn update_texture_image_from_video_frame(+ &mut self,+ command: &commands::TexSubImage2DFromBitmap,+ frame: &H::VideoFrame,+ frame_size: IntSize,+ ) -> bool {+ if !self+ .host+ .webgl_can_copy_images_into_textures(self.client, self.canvas_id)+ || format_is_integer(command.format)+ {+ return false;+ }+ let Some(size) = upload_size(+ frame_size,+ command.has_explicit_destination_size,+ command.destination_width,+ command.destination_height,+ ) else {+ return false;+ };+ let Some(image) = self.host.video_frame_image(frame) else {+ return false;+ };++ self.stash_errors();+ self.with_pixel_unpack_buffer_unbound(|| {+ // SAFETY: The context of the replayer is current, and GL reads no pixels.+ unsafe {+ (self.gl.tex_sub_image2d_robust_angle)(+ command.target,+ command.level,+ command.xoffset,+ command.yoffset,+ 0,+ 0,+ command.format,+ command.r#type,+ 0,+ core::ptr::null(),+ );+ }+ });+ if self.stash_errors() || size.is_empty() {+ return true;+ }+ let copy = VideoFrameCopy {+ source_size: frame_size,+ size,+ target: command.target,+ level: command.level,+ xoffset: command.xoffset,+ yoffset: command.yoffset,+ flip_y: command.flip_y,+ premultiply_alpha: command.premultiply_alpha,+ };+ if !self+ .host+ .copy_video_frame_image_into_bound_texture(self.client, self.canvas_id, &image, copy)+ {+ return false;+ }+ // NB: A region beyond the level is the caller's error, as it would be for an upload of pixels.+ self.stash_errors();+ true+ }++ fn held_video_frame_of(&self, source: ImageSource) -> Option<(H::VideoFrame, IntSize)> {+ let ImageSource::HeldVideoFrame {+ sink_handle,+ generation,+ } = source+ else {+ return None;+ };+ self.host.held_video_frame(self.client, sink_handle, generation)+ }++ pub(super) fn tex_image2d_from_bitmap(&mut self, payload: &[u8]) -> Result<(), ReplayError> {+ let command: commands::TexImage2DFromBitmap = decode(payload)?;+ let source = self.image_source_at(command.bitmap_index)?;+ if let Some((frame, frame_size)) = self.held_video_frame_of(source)+ && self.define_texture_image_from_video_frame(&command, &frame, frame_size)+ {+ return Ok(());+ }+ let Some(image) = self.converted_image(&image_upload!(command))? else {+ return Ok(());+ };+ let (pixels_size, pixels) = pixels_of(&image)?;+ self.with_packed_unpack_state(|| {+ // SAFETY: The context of the replayer is current, and the pixels have the size.+ unsafe {+ (self.gl.tex_image2d_robust_angle)(+ command.target,+ command.level,+ command.internalformat,+ image.width,+ image.height,+ 0,+ command.format,+ command.r#type,+ pixels_size,+ pixels,+ );+ }+ });+ Ok(())+ }++ pub(super) fn tex_sub_image2d_from_bitmap(&mut self, payload: &[u8]) -> Result<(), ReplayError> {+ let command: commands::TexSubImage2DFromBitmap = decode(payload)?;+ let source = self.image_source_at(command.bitmap_index)?;+ if let Some((frame, frame_size)) = self.held_video_frame_of(source)+ && self.update_texture_image_from_video_frame(&command, &frame, frame_size)+ {+ return Ok(());+ }+ let Some(image) = self.converted_image(&image_upload!(command))? else {+ return Ok(());+ };+ let (pixels_size, pixels) = pixels_of(&image)?;+ self.with_packed_unpack_state(|| {+ // SAFETY: The context of the replayer is current, and the pixels have the size.+ unsafe {+ (self.gl.tex_sub_image2d_robust_angle)(+ command.target,+ command.level,+ command.xoffset,+ command.yoffset,+ image.width,+ image.height,+ command.format,+ command.r#type,+ pixels_size,+ pixels,+ );+ }+ });+ Ok(())+ }++ pub(super) fn tex_image3d_from_bitmap(&mut self, payload: &[u8]) -> Result<(), ReplayError> {+ let command: commands::TexImage3DFromBitmap = decode(payload)?;+ let Some(image) = self.converted_image(&image_upload!(command))? else {+ return Ok(());+ };+ let (pixels_size, pixels) = pixels_of(&image)?;+ self.with_packed_unpack_state(|| {+ // SAFETY: The context of the replayer is current, and the pixels have the size.+ unsafe {+ (self.gl.tex_image3d_robust_angle)(+ command.target,+ command.level,+ command.internalformat,+ image.width,+ image.height,+ command.depth,+ 0,+ command.format,+ command.r#type,+ pixels_size,+ pixels,+ );+ }+ });+ Ok(())+ }++ pub(super) fn tex_sub_image3d_from_bitmap(&mut self, payload: &[u8]) -> Result<(), ReplayError> {+ let command: commands::TexSubImage3DFromBitmap = decode(payload)?;+ let Some(image) = self.converted_image(&image_upload!(command))? else {+ return Ok(());+ };+ let (pixels_size, pixels) = pixels_of(&image)?;+ self.with_packed_unpack_state(|| {+ // SAFETY: The context of the replayer is current, and the pixels have the size.+ unsafe {+ (self.gl.tex_sub_image3d_robust_angle)(+ command.target,+ command.level,+ command.xoffset,+ command.yoffset,+ command.zoffset,+ image.width,+ image.height,+ command.depth,+ command.format,+ command.r#type,+ pixels_size,+ pixels,+ );+ }+ });+ Ok(())+ }++ pub(super) fn get_string(&mut self, payload: &[u8]) -> Result<Vec<u8>, ReplayError> {+ let request: sync_calls::GetStringRequest = decode(payload)?;+ // SAFETY: The context of the replayer is current, and GL answers a string or null.+ let value = unsafe { (self.gl.get_string)(request.name) };+ let value: &[u8] = if value.is_null() {+ b"\0"+ } else {+ // SAFETY: GL answers a NUL-terminated string.+ unsafe { CStr::from_ptr(value.cast::<c_char>()) }.to_bytes_with_nul()+ };+ let [value_span] = reply_data_spans::<sync_calls::GetStringReply, 1>([value.len()]);+ let reply = sync_calls::GetStringReply { value: value_span };+ Ok(encode_reply(&reply, &[value]))+ }++ pub(super) fn get_vertex_attrib_pointerv_robust_angle(&mut self, payload: &[u8]) -> Result<Vec<u8>, ReplayError> {+ let request: sync_calls::GetVertexAttribPointervRobustANGLERequest = decode(payload)?;+ let mut pointer = core::ptr::null_mut();+ let mut length = 0;+ // SAFETY: The context of the replayer is current, and the pointer is room for one.+ unsafe {+ (self.gl.get_vertex_attrib_pointerv_robust_angle)(+ request.index,+ request.pname,+ 1,+ &raw mut length,+ &raw mut pointer,+ );+ }+ let reply = sync_calls::GetVertexAttribPointervRobustANGLEReply {+ pointer: pointer as usize as i64,+ };+ Ok(encode_reply(&reply, &[]))+ }++ pub(super) fn get_uniform_indices(&mut self, payload: &[u8]) -> Result<Vec<u8>, ReplayError> {+ let request: sync_calls::GetUniformIndicesRequest = decode(payload)?;+ let names = split_packed_strings(data_span(payload, request.uniform_names)?, request.uniform_count)?;+ let program = self.objects.lookup(request.program);+ let mut indices = vec![0_u32; names.len()];+ // SAFETY: The context of the replayer is current, every name is NUL-terminated, and there is room for an index+ // of each.+ unsafe {+ (self.gl.get_uniform_indices)(program, request.uniform_count, names.as_ptr(), indices.as_mut_ptr());+ }+ let indices = bytes_of_slice(&indices);+ let [indices_span] = reply_data_spans::<sync_calls::GetUniformIndicesReply, 1>([indices.len()]);+ let reply = sync_calls::GetUniformIndicesReply {+ uniform_indices: indices_span,+ };+ Ok(encode_reply(&reply, &[indices]))+ }+}diff --git a/Services/Compositor/Rust/src/webgl/gl.rs b/Services/Compositor/Rust/src/webgl/gl.rsnew file mode 100644index 00000000000..f1b436eda78--- /dev/null+++ b/Services/Compositor/Rust/src/webgl/gl.rs@@ -0,0 +1,12 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The GL functions that the replayer calls, which the build script lists from GLFunctions.json+//! (generate/webgl_replayer.rs). They are looked up rather than linked, so that the crate links without ANGLE.++#![allow(clippy::missing_safety_doc)]++include!(concat!(env!("OUT_DIR"), "/webgl_gl.rs"));diff --git a/Services/Compositor/Rust/src/webgl/gl_constants.rs b/Services/Compositor/Rust/src/webgl/gl_constants.rsnew file mode 100644index 00000000000..e493f1e47f2--- /dev/null+++ b/Services/Compositor/Rust/src/webgl/gl_constants.rs@@ -0,0 +1,66 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++pub const GL_NO_ERROR: u32 = 0;+pub const GL_COLOR: u32 = 0x1800;+pub const GL_EXTENSIONS: u32 = 0x1F03;+pub const GL_REQUESTABLE_EXTENSIONS_ANGLE: u32 = 0x93A8;++pub const GL_FRAMEBUFFER: u32 = 0x8D40;+pub const GL_DRAW_FRAMEBUFFER: u32 = 0x8CA9;+pub const GL_FRAMEBUFFER_BINDING: u32 = 0x8CA6;+pub const GL_DRAW_FRAMEBUFFER_BINDING: u32 = 0x8CA6;+pub const GL_RENDERBUFFER: u32 = 0x8D41;+pub const GL_RENDERBUFFER_BINDING: u32 = 0x8CA7;++pub const GL_COLOR_CLEAR_VALUE: u32 = 0x0C22;+pub const GL_DEPTH_CLEAR_VALUE: u32 = 0x0B73;+pub const GL_STENCIL_CLEAR_VALUE: u32 = 0x0B91;+pub const GL_COLOR_BUFFER_BIT: u32 = 0x4000;+pub const GL_DEPTH_BUFFER_BIT: u32 = 0x0100;+pub const GL_STENCIL_BUFFER_BIT: u32 = 0x0400;++pub const GL_UNPACK_ALIGNMENT: u32 = 0x0CF5;+pub const GL_UNPACK_ROW_LENGTH: u32 = 0x0CF2;+pub const GL_UNPACK_SKIP_PIXELS: u32 = 0x0CF4;+pub const GL_UNPACK_SKIP_ROWS: u32 = 0x0CF3;+pub const GL_UNPACK_IMAGE_HEIGHT: u32 = 0x806E;+pub const GL_UNPACK_SKIP_IMAGES: u32 = 0x806D;+pub const GL_PIXEL_UNPACK_BUFFER: u32 = 0x88EC;+pub const GL_PIXEL_UNPACK_BUFFER_BINDING: u32 = 0x88EF;+pub const GL_MAP_READ_BIT: u32 = 0x0001;++pub const GL_ALPHA: u32 = 0x1906;+pub const GL_RGB: u32 = 0x1907;+pub const GL_RGBA: u32 = 0x1908;+pub const GL_LUMINANCE: u32 = 0x1909;+pub const GL_LUMINANCE_ALPHA: u32 = 0x190A;+pub const GL_SRGB_EXT: u32 = 0x8C40;+pub const GL_SRGB_ALPHA_EXT: u32 = 0x8C42;+pub const GL_R8: u32 = 0x8229;+pub const GL_RG8: u32 = 0x822B;+pub const GL_RGB8: u32 = 0x8051;+pub const GL_RGBA8: u32 = 0x8058;+pub const GL_SRGB8: u32 = 0x8C41;+pub const GL_SRGB8_ALPHA8: u32 = 0x8C43;+pub const GL_RGB565: u32 = 0x8D62;+pub const GL_RGBA4: u32 = 0x8056;+pub const GL_RGB5_A1: u32 = 0x8057;+pub const GL_RGB10_A2: u32 = 0x8059;+pub const GL_RGB9_E5: u32 = 0x8C3D;+pub const GL_R11F_G11F_B10F: u32 = 0x8C3A;+pub const GL_R16F: u32 = 0x822D;+pub const GL_RG16F: u32 = 0x822F;+pub const GL_RGB16F: u32 = 0x881B;+pub const GL_RGBA16F: u32 = 0x881A;+pub const GL_R32F: u32 = 0x822E;+pub const GL_RG32F: u32 = 0x8230;+pub const GL_RGB32F: u32 = 0x8815;+pub const GL_RGBA32F: u32 = 0x8814;+pub const GL_RED_INTEGER: u32 = 0x8D94;+pub const GL_RG_INTEGER: u32 = 0x8228;+pub const GL_RGB_INTEGER: u32 = 0x8D98;+pub const GL_RGBA_INTEGER: u32 = 0x8D99;diff --git a/Services/Compositor/Rust/src/webgl/host.rs b/Services/Compositor/Rust/src/webgl/host.rsnew file mode 100644index 00000000000..9cf224c2341--- /dev/null+++ b/Services/Compositor/Rust/src/webgl/host.rs@@ -0,0 +1,152 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What the replay of WebGL asks of the C++ side: the GL contexts with their drawing buffers, which C++ makes current,+//! presents and reads back, and the images that it converts or copies for texture uploads.++use core::ffi::{CStr, c_void};++use libcompositing_rust::display_list::commands::{CanvasId, VideoSinkHandle};+use libcompositing_rust::webgl::ImageSource;+use libcompositing_rust::webgl::texture_upload::ExportFormat;+use libgfx_rust::{IntRect, IntSize};++use crate::host::WebContentClientId;++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+#[repr(C)]+pub struct DefaultBuffers {+ pub framebuffer: u32,+ pub renderbuffer: u32,+}++#[derive(Clone, Copy, Debug)]+#[repr(C)]+pub struct ContextOptions {+ pub webgl2: bool,+ pub depth: bool,+ pub stencil: bool,+ pub antialias: bool,+ pub size: IntSize,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+#[repr(u8)]+pub enum PresentOutcome {+ Presented,+ /// Nothing ran since the frame presented last, which the canvas went on showing.+ ShowedPresentedFrame,+ NoDrawingBuffer,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct ImageConversion {+ pub export_format: ExportFormat,+ pub flip_y: bool,+ pub premultiply_alpha: bool,+ pub target_size: Option<IntSize>,+}++pub enum ImageConversionOutcome<P> {+ Converted { pixels: P, width: i32, height: i32 },+ UnknownImageFrame,+ Failed,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct VideoFrameCopy {+ /// The part of the frame to copy, from its top left.+ pub source_size: IntSize,+ pub size: IntSize,+ pub target: u32,+ pub level: i32,+ pub xoffset: i32,+ pub yoffset: i32,+ pub flip_y: bool,+ pub premultiply_alpha: bool,+}++/// Shared memory that WebContent writes into while the Compositor reads it, so no Rust reference may cover it.+pub trait MappedMemory {+ fn as_mut_ptr(&self) -> *mut u8;+ fn len(&self) -> usize;++ fn is_empty(&self) -> bool {+ self.len() == 0+ }+}++impl MappedMemory for crate::raster_host::SharedMemory {+ fn as_mut_ptr(&self) -> *mut u8 {+ self.as_ptr()+ }++ fn len(&self) -> usize {+ self.len()+ }+}++pub trait WebGLHost {+ type Pixels: AsRef<[u8]>;+ type VideoFrame;+ type VideoFrameImage;++ /// The address of a GL function, or null.+ fn gl_proc_address(&self, name: &CStr) -> *const c_void;+ fn allocate_canvas_id(&self) -> CanvasId;+ /// Answers whether a GL context with a drawing buffer of the size could be made.+ fn create_webgl_context(&self, client: WebContentClientId, canvas_id: CanvasId, options: ContextOptions) -> bool;+ fn destroy_webgl_context(&self, client: WebContentClientId, canvas_id: CanvasId);+ /// Makes the GL context current, allocating its drawing buffer if it has to.+ fn make_webgl_context_current(&self, client: WebContentClientId, canvas_id: CanvasId) -> DefaultBuffers;+ fn set_webgl_drawing_buffer_size(&self, client: WebContentClientId, canvas_id: CanvasId, size: IntSize);+ /// Makes what was drawn the content of the canvas, or the frame presented last where `show_presented_frame` asks for+ /// it and there is one.+ fn present_webgl_context(+ &self,+ client: WebContentClientId,+ canvas_id: CanvasId,+ preserve_drawing_buffer: bool,+ show_presented_frame: bool,+ ) -> PresentOutcome;+ /// Writes the part of the drawing buffer, or of the frame presented last, that the rect covers to `pixels` as+ /// premultiplied BGRA8888 rows, and answers the size of that part.+ ///+ /// # Safety+ ///+ /// `pixels` is valid for writes of `pixels_size` bytes.+ unsafe fn read_back_webgl_drawing_buffer(+ &self,+ client: WebContentClientId,+ canvas_id: CanvasId,+ from_presented_frame: bool,+ rect: IntRect,+ pixels: *mut u8,+ pixels_size: usize,+ ) -> Option<IntSize>;+ fn webgl_can_copy_images_into_textures(&self, client: WebContentClientId, canvas_id: CanvasId) -> bool;+ /// The frame of the video that the client holds, with its size.+ fn held_video_frame(+ &self,+ client: WebContentClientId,+ sink_handle: VideoSinkHandle,+ generation: u64,+ ) -> Option<(Self::VideoFrame, IntSize)>;+ fn video_frame_image(&self, frame: &Self::VideoFrame) -> Option<Self::VideoFrameImage>;+ fn copy_video_frame_image_into_bound_texture(+ &self,+ client: WebContentClientId,+ canvas_id: CanvasId,+ image: &Self::VideoFrameImage,+ copy: VideoFrameCopy,+ ) -> bool;+ fn convert_image_source(+ &self,+ client: WebContentClientId,+ source: ImageSource,+ conversion: ImageConversion,+ ) -> ImageConversionOutcome<Self::Pixels>;+}diff --git a/Services/Compositor/Rust/src/webgl/mod.rs b/Services/Compositor/Rust/src/webgl/mod.rsnew file mode 100644index 00000000000..b3bdd1ed47a--- /dev/null+++ b/Services/Compositor/Rust/src/webgl/mod.rs@@ -0,0 +1,458 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The WebGL contexts of the clients: the GL contexts that C++ makes for them, and what replaying their commands needs+//! to know between messages.++pub mod custom;+pub mod gl;+pub mod gl_constants;+pub mod host;+pub mod object_map;+pub mod replay;+#[cfg(test)]+mod testing;+#[cfg(test)]+mod tests;++use std::collections::HashMap;+use std::sync::atomic::{AtomicU64, Ordering};++use libcompositing_rust::display_list::commands::CanvasId;+use libcompositing_rust::webgl::{ImageSource, SHARED_DATA_REGION_OFFSET};+use libgfx_rust::{IntRect, IntSize};++use self::custom::{clear_buffer_to_default_values, supported_extensions};+use self::gl::GlFunctions;+use self::gl_constants::GL_MAP_READ_BIT;+use self::host::{ContextOptions, DefaultBuffers, MappedMemory, PresentOutcome, WebGLHost};+use self::object_map::ObjectMap;+use self::replay::{ReplayError, Replayer};+use crate::host::WebContentClientId;++const MAX_DRAWING_BUFFER_DIMENSION: i32 = 16384;++/// A copy of what is replayed that holds more than this is not kept for the next message.+const MAX_KEPT_SCRATCH_SIZE: usize = 1024 * 1024;++pub struct CreatedContext {+ pub canvas_id: CanvasId,+ pub supported_extensions: Vec<String>,+}++pub struct ReadPixelsResult {+ pub length: i32,+ pub columns: i32,+ pub rows: i32,+}++struct WebGLContext {+ webgl2: bool,+ objects: ObjectMap,+ command_buffer: Option<Box<dyn MappedMemory>>,+ /// A drawing buffer that is not preserved is cleared before the next command that draws or reads after the frame+ /// was presented, which goes on being the content of the canvas until then.+ needs_clear_before_next_frame: bool,+ stashed_errors: Vec<u32>,+ /// Where what is replayed is copied to, so that WebContent cannot change it while it is checked and replayed. Its+ /// elements keep the data of the records aligned as WebContent wrote it.+ scratch: Vec<u64>,+}++impl WebGLContext {+ fn new(webgl2: bool) -> Self {+ Self {+ webgl2,+ objects: ObjectMap::default(),+ command_buffer: None,+ needs_clear_before_next_frame: false,+ stashed_errors: Vec::new(),+ scratch: Vec::new(),+ }+ }++ fn give_back_scratch(&mut self, scratch: Vec<u64>) {+ if scratch.capacity() * size_of::<u64>() <= MAX_KEPT_SCRATCH_SIZE {+ self.scratch = scratch;+ }+ }+}++/// Copies bytes that WebContent can write while they are replayed into the scratch, which keeps the data of the records+/// as aligned as WebContent wrote it, and answers the copy.+///+/// # Safety+///+/// `bytes` is valid for reads of `size` bytes.+unsafe fn copy_to_scratch(scratch: &mut Vec<u64>, bytes: *const u8, size: usize) -> &[u8] {+ scratch.clear();+ scratch.resize(size.div_ceil(size_of::<u64>()), 0);+ // SAFETY: The caller passes as many readable bytes, and the scratch has room for them.+ unsafe {+ core::ptr::copy_nonoverlapping(bytes, scratch.as_mut_ptr().cast::<u8>(), size);+ ak::slice_from_raw_parts(scratch.as_ptr().cast::<u8>(), size)+ }+}++#[derive(Default)]+pub struct WebGLContexts {+ gl: Option<Box<GlFunctions>>,+ clients: HashMap<WebContentClientId, HashMap<CanvasId, WebGLContext>>,+}++impl WebGLContexts {+ #[cfg(test)]+ fn with_gl_functions(gl: GlFunctions) -> Self {+ Self {+ gl: Some(Box::new(gl)),+ clients: HashMap::new(),+ }+ }++ fn context_and_gl(+ &mut self,+ client: WebContentClientId,+ canvas_id: CanvasId,+ ) -> Result<(&mut WebGLContext, &GlFunctions), ReplayError> {+ let context = self+ .clients+ .get_mut(&client)+ .and_then(|contexts| contexts.get_mut(&canvas_id))+ .ok_or(ReplayError("WebContent named a WebGL context that it has not created"))?;+ let gl = self+ .gl+ .as_deref()+ .expect("the GL functions are loaded before the first context is created");+ Ok((context, gl))+ }++ /// None where the context could not be created, which is no misbehavior: the canvas has no context then.+ pub fn create<H: WebGLHost>(+ &mut self,+ host: &H,+ client: WebContentClientId,+ options: ContextOptions,+ ) -> Option<CreatedContext> {+ let dimensions = 1..=MAX_DRAWING_BUFFER_DIMENSION;+ if !dimensions.contains(&options.size.width) || !dimensions.contains(&options.size.height) {+ return None;+ }+ let canvas_id = host.allocate_canvas_id();+ if !host.create_webgl_context(client, canvas_id, options) {+ return None;+ }+ if self.gl.is_none() {+ // SAFETY: The host answers the address of a GL function or null.+ match unsafe { GlFunctions::load(|name| host.gl_proc_address(name)) } {+ Ok(gl) => self.gl = Some(Box::new(gl)),+ Err(missing_function) => {+ eprintln!("Compositor: Cannot replay WebGL without {missing_function:?}");+ host.destroy_webgl_context(client, canvas_id);+ return None;+ }+ }+ }+ let gl = self.gl.as_deref().expect("the GL functions are loaded");+ host.make_webgl_context_current(client, canvas_id);+ let supported_extensions = supported_extensions(gl);+ self.clients+ .entry(client)+ .or_default()+ .insert(canvas_id, WebGLContext::new(options.webgl2));+ Some(CreatedContext {+ canvas_id,+ supported_extensions,+ })+ }++ /// A context that is gone already is no misbehavior, as it is not for a 2D canvas.+ pub fn destroy<H: WebGLHost>(&mut self, host: &H, client: WebContentClientId, canvas_id: CanvasId) {+ if self+ .clients+ .get_mut(&client)+ .and_then(|contexts| contexts.remove(&canvas_id))+ .is_some()+ {+ host.destroy_webgl_context(client, canvas_id);+ }+ }++ /// The C++ side destroys the GL contexts of a client that went away with the rest of what it holds for it.+ pub fn forget_client(&mut self, client: WebContentClientId) {+ self.clients.remove(&client);+ }++ pub fn set_command_buffer(+ &mut self,+ client: WebContentClientId,+ canvas_id: CanvasId,+ command_buffer: Option<Box<dyn MappedMemory>>,+ ) -> Result<(), ReplayError> {+ let (context, _) = self.context_and_gl(client, canvas_id)?;+ let command_buffer = command_buffer+ .filter(|command_buffer| command_buffer.len() > SHARED_DATA_REGION_OFFSET)+ .ok_or(ReplayError("WebContent sent an invalid WebGL shared command buffer"))?;+ context.command_buffer = Some(command_buffer);+ Ok(())+ }++ fn replay<H: WebGLHost>(+ context: &mut WebGLContext,+ gl: &GlFunctions,+ host: &H,+ client: WebContentClientId,+ canvas_id: CanvasId,+ image_sources: &[ImageSource],+ commands: impl FnOnce(&mut Replayer<'_, H>) -> Result<(), ReplayError>,+ ) -> Result<(), ReplayError> {+ let defaults = host.make_webgl_context_current(client, canvas_id);+ clear_drawing_buffer_if_needed(context, gl, defaults);+ let mut replayer = Replayer {+ gl,+ host,+ client,+ canvas_id,+ webgl2: context.webgl2,+ objects: &mut context.objects,+ stashed_errors: &mut context.stashed_errors,+ defaults,+ image_sources,+ };+ commands(&mut replayer)+ }++ #[allow(clippy::too_many_arguments)]+ pub fn execute_commands_from_shared_buffer<H: WebGLHost>(+ &mut self,+ host: &H,+ client: WebContentClientId,+ canvas_id: CanvasId,+ offset: u64,+ size_in_bytes: u64,+ flush_sequence_number: u64,+ image_sources: &[ImageSource],+ ) -> Result<(), ReplayError> {+ let (context, gl) = self.context_and_gl(client, canvas_id)?;+ let Some(command_buffer) = context.command_buffer.as_deref() else {+ return Err(ReplayError(+ "WebContent published WebGL commands without a shared command buffer",+ ));+ };+ let base = command_buffer.as_mut_ptr();+ let region_size = command_buffer.len() - SHARED_DATA_REGION_OFFSET;+ let range = usize::try_from(offset)+ .ok()+ .zip(usize::try_from(size_in_bytes).ok())+ .filter(|&(offset, size)| {+ offset.is_multiple_of(libcompositing_rust::webgl::wire::RECORD_ALIGNMENT)+ && offset <= region_size+ && size <= region_size - offset+ });+ let Some((offset, size)) = range else {+ return Err(ReplayError(+ "WebContent published an invalid WebGL shared command buffer range",+ ));+ };+ let mut scratch = core::mem::take(&mut context.scratch);+ // SAFETY: The range lies inside the region of records of the mapping, which is readable.+ let commands = unsafe { copy_to_scratch(&mut scratch, base.add(SHARED_DATA_REGION_OFFSET + offset), size) };+ // NB: The records were copied, so WebContent may write over them once it learns that they were taken.+ // SAFETY: The mapping starts at a page, where the u64 that the sequence number is stored in is, and WebContent+ // only reads it.+ unsafe { AtomicU64::from_ptr(base.cast::<u64>()) }.store(flush_sequence_number, Ordering::Release);+ let result = Self::replay(context, gl, host, client, canvas_id, image_sources, |replayer| {+ replayer.replay_commands(commands)+ });+ context.give_back_scratch(scratch);+ result+ }++ pub fn execute_commands<H: WebGLHost>(+ &mut self,+ host: &H,+ client: WebContentClientId,+ canvas_id: CanvasId,+ commands: Option<&dyn MappedMemory>,+ image_sources: &[ImageSource],+ ) -> Result<(), ReplayError> {+ let (context, gl) = self.context_and_gl(client, canvas_id)?;+ let commands = commands.ok_or(ReplayError("WebContent sent an invalid WebGL command buffer"))?;+ let mut scratch = core::mem::take(&mut context.scratch);+ // SAFETY: The mapping holds as many readable bytes.+ let commands = unsafe { copy_to_scratch(&mut scratch, commands.as_mut_ptr(), commands.len()) };+ let result = Self::replay(context, gl, host, client, canvas_id, image_sources, |replayer| {+ replayer.replay_commands(commands)+ });+ context.give_back_scratch(scratch);+ result+ }++ pub fn execute_sync_call<H: WebGLHost>(+ &mut self,+ host: &H,+ client: WebContentClientId,+ canvas_id: CanvasId,+ request: &[u8],+ ) -> Result<Vec<u8>, ReplayError> {+ let (context, gl) = self.context_and_gl(client, canvas_id)?;+ let mut scratch = core::mem::take(&mut context.scratch);+ // SAFETY: The request is readable.+ let request = unsafe { copy_to_scratch(&mut scratch, request.as_ptr(), request.len()) };+ let mut reply = Vec::new();+ let result = Self::replay(context, gl, host, client, canvas_id, &[], |replayer| {+ reply = replayer.handle_sync_request(request)?;+ Ok(())+ });+ context.give_back_scratch(scratch);+ result.map(|()| reply)+ }++ pub fn present<H: WebGLHost>(+ &mut self,+ host: &H,+ client: WebContentClientId,+ canvas_id: CanvasId,+ preserve_drawing_buffer: bool,+ ) -> Result<(), ReplayError> {+ let (context, _) = self.context_and_gl(client, canvas_id)?;+ match host.present_webgl_context(+ client,+ canvas_id,+ preserve_drawing_buffer,+ context.needs_clear_before_next_frame,+ ) {+ PresentOutcome::Presented => {+ if !preserve_drawing_buffer {+ context.needs_clear_before_next_frame = true;+ }+ }+ PresentOutcome::ShowedPresentedFrame => {}+ PresentOutcome::NoDrawingBuffer => {+ eprintln!("Compositor: Cannot present a WebGL context without a drawing buffer");+ }+ }+ Ok(())+ }++ /// A context that is gone already is left alone.+ pub fn clear_drawing_buffer<H: WebGLHost>(&mut self, host: &H, client: WebContentClientId, canvas_id: CanvasId) {+ let Ok((context, gl)) = self.context_and_gl(client, canvas_id) else {+ return;+ };+ let defaults = host.make_webgl_context_current(client, canvas_id);+ clear_buffer_to_default_values(gl, context.webgl2, defaults);+ context.needs_clear_before_next_frame = false;+ }++ #[allow(clippy::too_many_arguments)]+ pub fn read_pixels<H: WebGLHost>(+ &mut self,+ host: &H,+ client: WebContentClientId,+ canvas_id: CanvasId,+ rect: IntRect,+ format: u32,+ r#type: u32,+ buffer_size: i32,+ pixels: Option<&dyn MappedMemory>,+ ) -> Result<ReadPixelsResult, ReplayError> {+ let (context, gl) = self.context_and_gl(client, canvas_id)?;+ let pixels_size = pixels.map_or(0, |pixels| pixels.len());+ if usize::try_from(buffer_size).map_or(true, |buffer_size| buffer_size > pixels_size) {+ return Err(ReplayError("WebContent sent an invalid WebGL readPixels buffer"));+ }+ let defaults = host.make_webgl_context_current(client, canvas_id);+ clear_drawing_buffer_if_needed(context, gl, defaults);+ let mut result = ReadPixelsResult {+ length: 0,+ columns: 0,+ rows: 0,+ };+ let destination = pixels.map_or(core::ptr::null_mut(), |pixels| pixels.as_mut_ptr());+ // SAFETY: The context is current, and GL writes at most `buffer_size` bytes, which the mapping holds.+ unsafe {+ (gl.read_pixels_robust_angle)(+ rect.x,+ rect.y,+ rect.width,+ rect.height,+ format,+ r#type,+ buffer_size,+ &raw mut result.length,+ &raw mut result.columns,+ &raw mut result.rows,+ destination.cast(),+ );+ }+ Ok(result)+ }++ #[allow(clippy::too_many_arguments)]+ pub fn read_buffer_sub_data<H: WebGLHost>(+ &mut self,+ host: &H,+ client: WebContentClientId,+ canvas_id: CanvasId,+ target: u32,+ offset: i64,+ size: i64,+ data: Option<&dyn MappedMemory>,+ ) -> Result<bool, ReplayError> {+ let (_, gl) = self.context_and_gl(client, canvas_id)?;+ let data_size = data.map_or(0, |data| data.len());+ let Some(size) = usize::try_from(size).ok().filter(|&size| size <= data_size) else {+ return Err(ReplayError("WebContent sent an invalid WebGL buffer readback target"));+ };+ host.make_webgl_context_current(client, canvas_id);+ // SAFETY: The context is current.+ let mapped = unsafe { (gl.map_buffer_range)(target, offset as isize, size as isize, GL_MAP_READ_BIT) };+ if mapped.is_null() {+ return Ok(false);+ }+ if let Some(data) = data {+ // SAFETY: GL mapped `size` bytes of the buffer, and the shared memory holds at least as many.+ unsafe { core::ptr::copy_nonoverlapping(mapped.cast::<u8>(), data.as_mut_ptr(), size) };+ }+ // SAFETY: The context is current, and the buffer of the target is mapped.+ unsafe { (gl.unmap_buffer)(target) };+ Ok(true)+ }++ pub fn read_back_drawing_buffer<H: WebGLHost>(+ &mut self,+ host: &H,+ client: WebContentClientId,+ canvas_id: CanvasId,+ rect: IntRect,+ pixels: Option<&dyn MappedMemory>,+ ) -> Result<IntSize, ReplayError> {+ let (context, _) = self.context_and_gl(client, canvas_id)?;+ let Some(pixels) = pixels else {+ return Ok(IntSize::default());+ };+ // SAFETY: The mapping holds as many writable bytes.+ let size = unsafe {+ host.read_back_webgl_drawing_buffer(+ client,+ canvas_id,+ context.needs_clear_before_next_frame,+ rect,+ pixels.as_mut_ptr(),+ pixels.len(),+ )+ };+ Ok(size.unwrap_or_default())+ }+}++fn clear_drawing_buffer_if_needed(context: &mut WebGLContext, gl: &GlFunctions, defaults: DefaultBuffers) {+ if !context.needs_clear_before_next_frame {+ return;+ }+ clear_buffer_to_default_values(gl, context.webgl2, defaults);+ context.needs_clear_before_next_frame = false;+}diff --git a/Services/Compositor/Rust/src/webgl/object_map.rs b/Services/Compositor/Rust/src/webgl/object_map.rsnew file mode 100644index 00000000000..8aeab2d06df--- /dev/null+++ b/Services/Compositor/Rust/src/webgl/object_map.rs@@ -0,0 +1,56 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The GL objects of a context by the ids that WebContent gave them.++use core::ffi::c_void;+use std::collections::HashMap;++use super::replay::ReplayError;++#[derive(Default)]+pub struct ObjectMap {+ objects: HashMap<u32, u32>,+ syncs: HashMap<u32, *mut c_void>,+}++fn add_unique<V>(map: &mut HashMap<u32, V>, id: u32, value: V) -> Result<(), ReplayError> {+ if id == 0 {+ return Err(ReplayError("WebGL object id 0 is reserved"));+ }+ if map.contains_key(&id) {+ return Err(ReplayError("WebGL object id is already in use"));+ }+ map.insert(id, value);+ Ok(())+}++impl ObjectMap {+ /// 0 for an id that names no object.+ pub fn lookup(&self, id: u32) -> u32 {+ self.objects.get(&id).copied().unwrap_or(0)+ }++ pub fn take(&mut self, id: u32) -> u32 {+ self.objects.remove(&id).unwrap_or(0)+ }++ pub fn add(&mut self, id: u32, name: u32) -> Result<(), ReplayError> {+ add_unique(&mut self.objects, id, name)+ }++ pub fn lookup_sync(&self, id: u32) -> *mut c_void {+ self.syncs.get(&id).copied().unwrap_or(core::ptr::null_mut())+ }++ pub fn take_sync(&mut self, id: u32) -> *mut c_void {+ self.syncs.remove(&id).unwrap_or(core::ptr::null_mut())+ }++ pub fn add_sync(&mut self, id: u32, sync: *mut c_void) -> Result<(), ReplayError> {+ add_unique(&mut self.syncs, id, sync)+ }+}diff --git a/Services/Compositor/Rust/src/webgl/replay.rs b/Services/Compositor/Rust/src/webgl/replay.rsnew file mode 100644index 00000000000..4b9055b8bff--- /dev/null+++ b/Services/Compositor/Rust/src/webgl/replay.rs@@ -0,0 +1,174 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The replay of the commands and the synchronous calls of one WebGL context, on a copy of what WebContent sent: every+//! struct, span and size is checked before GL sees it, and object ids become the names of GL objects.++use core::ffi::{c_char, c_void};++use libcompositing_rust::display_list::commands::CanvasId;+use libcompositing_rust::webgl::ImageSource;+use libcompositing_rust::webgl::vocabulary::{CommandType, SyncCallType, commands, sync_calls};+use libcompositing_rust::webgl::wire::{+ DataSpan, WireStruct, decode_sync_request, encode_reply, records, reply_data_spans,+};++use super::gl::GlFunctions;+use super::gl_constants::{GL_COLOR, GL_NO_ERROR};+use super::host::{DefaultBuffers, WebGLHost};+use super::object_map::ObjectMap;+use crate::host::WebContentClientId;++/// What WebContent sent that it must not send.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct ReplayError(pub &'static str);++/// A buffer that a synchronous call fills is never bigger than this.+const MAX_OUT_DATA_SIZE: usize = 64 * 1024 * 1024;++pub struct Replayer<'a, H: WebGLHost> {+ pub gl: &'a GlFunctions,+ pub host: &'a H,+ pub client: WebContentClientId,+ pub canvas_id: CanvasId,+ pub webgl2: bool,+ pub objects: &'a mut ObjectMap,+ pub stashed_errors: &'a mut Vec<u32>,+ pub defaults: DefaultBuffers,+ pub image_sources: &'a [ImageSource],+}++impl<H: WebGLHost> Replayer<'_, H> {+ pub fn replay_commands(&mut self, commands: &[u8]) -> Result<(), ReplayError> {+ for record in records(commands) {+ let (command_type, payload) = record.map_err(ReplayError)?;+ self.replay_record(command_type, payload)?;+ }+ Ok(())+ }++ pub fn handle_sync_request(&mut self, request: &[u8]) -> Result<Vec<u8>, ReplayError> {+ let (call_type, payload) = decode_sync_request(request).map_err(ReplayError)?;+ self.handle_sync_call(call_type, payload)+ }++ /// The errors that the Compositor's own GL work raised are kept apart, for WebGL to collect before those of GL.+ pub fn get_error(&mut self) -> u32 {+ if self.stashed_errors.is_empty() {+ // SAFETY: The context of the replayer is current.+ return unsafe { (self.gl.get_error)() };+ }+ self.stashed_errors.remove(0)+ }++ /// Answers whether GL had errors to stash.+ pub fn stash_errors(&mut self) -> bool {+ let mut stashed_any_errors = false;+ loop {+ // SAFETY: The context of the replayer is current.+ let error = unsafe { (self.gl.get_error)() };+ if error == GL_NO_ERROR {+ return stashed_any_errors;+ }+ if !self.stashed_errors.contains(&error) {+ self.stashed_errors.push(error);+ }+ stashed_any_errors = true;+ }+ }++ pub fn discard_errors(&mut self) {+ loop {+ // SAFETY: The context of the replayer is current.+ let error = unsafe { (self.gl.get_error)() };+ if error == GL_NO_ERROR {+ return;+ }+ eprintln!("Compositor: Discarding GL error {error:#x} raised by the Compositor's own work");+ }+ }+}++pub(super) fn decode<S: WireStruct>(payload: &[u8]) -> Result<S, ReplayError> {+ S::read_from(payload).ok_or(ReplayError("WebGL payload does not hold its struct"))+}++pub(super) fn data_span(payload: &[u8], span: DataSpan) -> Result<&[u8], ReplayError> {+ let start = span.offset as usize;+ start+ .checked_add(span.size as usize)+ .and_then(|end| payload.get(start..end))+ .ok_or(ReplayError("WebGL data span lies outside its payload"))+}++pub(super) fn typed_data<T>(bytes: &[u8]) -> Result<*const T, ReplayError> {+ if !bytes.as_ptr().cast::<T>().is_aligned() || !bytes.len().is_multiple_of(size_of::<T>()) {+ return Err(ReplayError("WebGL data does not hold whole values"));+ }+ Ok(bytes.as_ptr().cast())+}++/// A string that ends at the last byte of its span.+pub(super) fn string_data(payload: &[u8], span: DataSpan) -> Result<*const c_char, ReplayError> {+ let bytes = data_span(payload, span)?;+ if bytes.last() != Some(&0) {+ return Err(ReplayError("WebGL string is not NUL-terminated"));+ }+ Ok(bytes.as_ptr().cast())+}++pub(super) fn object_ids(bytes: &[u8]) -> Result<impl ExactSizeIterator<Item = u32>, ReplayError> {+ let (ids, rest) = bytes.as_chunks::<{ size_of::<u32>() }>();+ if !rest.is_empty() {+ return Err(ReplayError("WebGL object ids do not fill their span"));+ }+ Ok(ids.iter().map(|id| u32::from_ne_bytes(*id)))+}++fn product(factors: &[i64]) -> Option<i64> {+ factors+ .iter()+ .try_fold(1_i64, |product, &factor| product.checked_mul(factor))+}++/// Whether data is as big as the factors that its arguments give.+pub(super) fn size_matches(size: usize, factors: &[i64]) -> bool {+ product(factors).is_some_and(|expected| i64::try_from(size) == Ok(expected))+}++/// The size of a buffer that a synchronous call fills, which its arguments give.+pub(super) fn out_data_size(factors: &[i64]) -> Result<usize, ReplayError> {+ product(factors)+ .and_then(|size| usize::try_from(size).ok())+ .filter(|&size| size <= MAX_OUT_DATA_SIZE)+ .ok_or(ReplayError("WebGL asks for a buffer of a size that it cannot have"))+}++pub(super) fn bytes_of_slice<T: Copy>(values: &[T]) -> &[u8] {+ // SAFETY: The values are plain numbers or pointers, every byte of which is initialized.+ unsafe { ak::slice_from_raw_parts(values.as_ptr().cast(), size_of_val(values)) }+}++/// Splits `count` strings that follow each other, each with a NUL after it.+pub(super) fn split_packed_strings(bytes: &[u8], count: i32) -> Result<Vec<*const c_char>, ReplayError> {+ const MAX_STRING_LIST_ENTRIES: i32 = 16384;+ if !(0..=MAX_STRING_LIST_ENTRIES).contains(&count) {+ return Err(ReplayError("WebGL string list is too long"));+ }+ let mut strings = Vec::with_capacity(count as usize);+ let mut rest = bytes;+ for _ in 0..count {+ let end = rest+ .iter()+ .position(|&byte| byte == 0)+ .ok_or(ReplayError("WebGL string is not NUL-terminated"))?;+ strings.push(rest.as_ptr().cast());+ rest = &rest[end + 1..];+ }+ Ok(strings)+}++include!(concat!(env!("OUT_DIR"), "/webgl_replayer.rs"));diff --git a/Services/Compositor/Rust/src/webgl/testing.rs b/Services/Compositor/Rust/src/webgl/testing.rsnew file mode 100644index 00000000000..bc58f234b8d--- /dev/null+++ b/Services/Compositor/Rust/src/webgl/testing.rs@@ -0,0 +1,213 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use core::cell::{Cell, RefCell};+use core::ffi::{CStr, c_void};++use libcompositing_rust::display_list::commands::{CanvasId, VideoSinkHandle};+use libcompositing_rust::webgl::ImageSource;+use libgfx_rust::{IntRect, IntSize};++use super::host::{+ ContextOptions, DefaultBuffers, ImageConversion, ImageConversionOutcome, MappedMemory, PresentOutcome,+ VideoFrameCopy, WebGLHost,+};+use crate::host::WebContentClientId;++thread_local! {+ static CALLS: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };+ static NEXT_NAME: Cell<u32> = const { Cell::new(1) };+}++pub fn record(call: String) {+ CALLS.with_borrow_mut(|calls| calls.push(call));+}++pub fn take_calls() -> Vec<String> {+ CALLS.take()+}++pub fn next_name() -> u32 {+ NEXT_NAME.replace(NEXT_NAME.get() + 1)+}++pub fn reset() {+ take_calls();+ NEXT_NAME.set(1);+}++pub struct TestMemory {+ data: *mut u8,+ len: usize,+ _storage: Box<[u64]>,+}++impl TestMemory {+ pub fn new(bytes: &[u8]) -> Self {+ let mut storage = vec![0_u64; bytes.len().div_ceil(8)].into_boxed_slice();+ let data = storage.as_mut_ptr().cast::<u8>();+ // SAFETY: The storage has room for the bytes.+ unsafe { core::ptr::copy_nonoverlapping(bytes.as_ptr(), data, bytes.len()) };+ Self {+ data,+ len: bytes.len(),+ _storage: storage,+ }+ }++ pub fn bytes(&self) -> &[u8] {+ // SAFETY: The storage holds `len` bytes, and nothing else writes them during a test.+ unsafe { ak::slice_from_raw_parts(self.data, self.len) }+ }+}++impl MappedMemory for TestMemory {+ fn as_mut_ptr(&self) -> *mut u8 {+ self.data+ }++ fn len(&self) -> usize {+ self.len+ }+}++pub struct FakeHost {+ pub next_canvas_id: Cell<u64>,+ pub defaults: Cell<DefaultBuffers>,+ pub can_copy_images_into_textures: Cell<bool>,+ pub held_video_frame_size: Cell<Option<IntSize>>,+ pub copy_succeeds: Cell<bool>,+ pub conversion: RefCell<Option<ImageConversionOutcome<Vec<u8>>>>,+ pub has_presented_frame: Cell<bool>,+}++impl Default for FakeHost {+ fn default() -> Self {+ Self {+ next_canvas_id: Cell::new(1),+ defaults: Cell::new(DefaultBuffers {+ framebuffer: 100,+ renderbuffer: 200,+ }),+ can_copy_images_into_textures: Cell::new(false),+ held_video_frame_size: Cell::new(None),+ copy_succeeds: Cell::new(true),+ conversion: RefCell::new(None),+ has_presented_frame: Cell::new(false),+ }+ }+}++impl WebGLHost for FakeHost {+ type Pixels = Vec<u8>;+ type VideoFrame = u64;+ type VideoFrameImage = u64;++ fn gl_proc_address(&self, _: &CStr) -> *const c_void {+ core::ptr::null()+ }++ fn allocate_canvas_id(&self) -> CanvasId {+ CanvasId(self.next_canvas_id.replace(self.next_canvas_id.get() + 1))+ }++ fn create_webgl_context(&self, client: WebContentClientId, canvas_id: CanvasId, options: ContextOptions) -> bool {+ record(format!(+ "host.create({}, {}, {}x{})",+ client.0, canvas_id.0, options.size.width, options.size.height+ ));+ true+ }++ fn destroy_webgl_context(&self, client: WebContentClientId, canvas_id: CanvasId) {+ record(format!("host.destroy({}, {})", client.0, canvas_id.0));+ }++ fn make_webgl_context_current(&self, _: WebContentClientId, _: CanvasId) -> DefaultBuffers {+ record("host.make_current".into());+ self.defaults.get()+ }++ fn set_webgl_drawing_buffer_size(&self, _: WebContentClientId, _: CanvasId, size: IntSize) {+ record(format!("host.set_size({}x{})", size.width, size.height));+ }++ fn present_webgl_context(+ &self,+ _: WebContentClientId,+ _: CanvasId,+ preserve_drawing_buffer: bool,+ show_presented_frame: bool,+ ) -> PresentOutcome {+ record(format!(+ "host.present({preserve_drawing_buffer}, {show_presented_frame})"+ ));+ if show_presented_frame && self.has_presented_frame.get() {+ return PresentOutcome::ShowedPresentedFrame;+ }+ self.has_presented_frame.set(true);+ PresentOutcome::Presented+ }++ unsafe fn read_back_webgl_drawing_buffer(+ &self,+ _: WebContentClientId,+ _: CanvasId,+ from_presented_frame: bool,+ rect: IntRect,+ _: *mut u8,+ _: usize,+ ) -> Option<IntSize> {+ record(format!("host.read_back({from_presented_frame})"));+ Some(IntSize {+ width: rect.width,+ height: rect.height,+ })+ }++ fn webgl_can_copy_images_into_textures(&self, _: WebContentClientId, _: CanvasId) -> bool {+ record("host.can_copy".into());+ self.can_copy_images_into_textures.get()+ }++ fn held_video_frame(+ &self,+ _: WebContentClientId,+ sink_handle: VideoSinkHandle,+ generation: u64,+ ) -> Option<(u64, IntSize)> {+ record(format!("host.held_video_frame({}, {generation})", sink_handle.0));+ self.held_video_frame_size.get().map(|size| (sink_handle.0, size))+ }++ fn video_frame_image(&self, frame: &u64) -> Option<u64> {+ record(format!("host.video_frame_image({frame})"));+ Some(*frame)+ }++ fn copy_video_frame_image_into_bound_texture(+ &self,+ _: WebContentClientId,+ _: CanvasId,+ image: &u64,+ copy: VideoFrameCopy,+ ) -> bool {+ record(format!("host.copy({image}, {}x{})", copy.size.width, copy.size.height));+ self.copy_succeeds.get()+ }++ fn convert_image_source(+ &self,+ _: WebContentClientId,+ source: ImageSource,+ conversion: ImageConversion,+ ) -> ImageConversionOutcome<Vec<u8>> {+ record(format!("host.convert({source:?}, {:?})", conversion.export_format));+ self.conversion+ .take()+ .expect("the test sets up what the conversion answers")+ }+}diff --git a/Services/Compositor/Rust/src/webgl/tests.rs b/Services/Compositor/Rust/src/webgl/tests.rsnew file mode 100644index 00000000000..ce951e7341b--- /dev/null+++ b/Services/Compositor/Rust/src/webgl/tests.rs@@ -0,0 +1,706 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use libcompositing_rust::display_list::commands::{CanvasId, ImageFrameResourceId, VideoSinkHandle};+use libcompositing_rust::webgl::ImageSource;+use libcompositing_rust::webgl::SHARED_DATA_REGION_OFFSET;+use libcompositing_rust::webgl::vocabulary::{commands, sync_calls};+use libcompositing_rust::webgl::wire::{+ Command, DataSpan, InlineData, Record, SyncReply, WireStruct, encode_sync_request, resolve_data_span,+};+use libgfx_rust::{IntRect, IntSize};++use super::gl::recording;+use super::host::{ContextOptions, ImageConversionOutcome};+use super::replay::ReplayError;+use super::testing::{FakeHost, TestMemory, record, reset, take_calls};+use super::{WebGLContexts, gl_constants::*};+use crate::host::WebContentClientId;++const CLIENT: WebContentClientId = WebContentClientId(7);+const GL_ARRAY_BUFFER: u32 = 0x8892;+const GL_STATIC_DRAW: u32 = 0x88E4;+const GL_TEXTURE_2D: u32 = 0x0DE1;+const GL_UNSIGNED_BYTE: u32 = 0x1401;+const GL_FLOAT: u32 = 0x1406;+const GL_SYNC_GPU_COMMANDS_COMPLETE: u32 = 0x9117;++fn options(webgl2: bool) -> ContextOptions {+ ContextOptions {+ webgl2,+ depth: true,+ stencil: false,+ antialias: true,+ size: IntSize {+ width: 300,+ height: 150,+ },+ }+}++fn contexts_with_one(host: &FakeHost, webgl2: bool) -> (WebGLContexts, CanvasId) {+ reset();+ let mut contexts = WebGLContexts::with_gl_functions(recording::functions());+ let created = contexts+ .create(host, CLIENT, options(webgl2))+ .expect("the context is created");+ take_calls();+ (contexts, created.canvas_id)+}++fn record_of<C: Command>(command: &C, data: InlineData<'_>) -> Vec<u8> {+ Record::new(C::TYPE, command.as_bytes(), data).unwrap().encoded()+}++fn replay(+ contexts: &mut WebGLContexts,+ host: &FakeHost,+ canvas_id: CanvasId,+ records: &[Vec<u8>],+ image_sources: &[ImageSource],+) -> Result<(), ReplayError> {+ let commands = TestMemory::new(&records.concat());+ contexts.execute_commands(host, CLIENT, canvas_id, Some(&commands), image_sources)+}++fn ids(ids: &[u32]) -> Vec<u8> {+ ids.iter().flat_map(|id| id.to_ne_bytes()).collect()+}++fn gen_buffers(ids_bytes: &[u8], count: i32) -> Vec<u8> {+ let data = InlineData::Bytes(ids_bytes);+ record_of(+ &commands::GenBuffers {+ n: count,+ buffers: DataSpan::following::<commands::GenBuffers>(data),+ },+ data,+ )+}++#[test]+fn objects_are_named_by_the_ids_that_webcontent_gave_them() {+ let host = FakeHost::default();+ let (mut contexts, canvas_id) = contexts_with_one(&host, false);+ let delete_ids = ids(&[2, 1]);+ let delete_data = InlineData::Bytes(&delete_ids);+ let records = [+ gen_buffers(&ids(&[1, 2]), 2),+ record_of(+ &commands::BindBuffer {+ target: GL_ARRAY_BUFFER,+ buffer: 2,+ },+ InlineData::NONE,+ ),+ record_of(+ &commands::DeleteBuffers {+ n: 2,+ buffers: DataSpan::following::<commands::DeleteBuffers>(delete_data),+ },+ delete_data,+ ),+ record_of(+ &commands::BindBuffer {+ target: GL_ARRAY_BUFFER,+ buffer: 2,+ },+ InlineData::NONE,+ ),+ ];+ replay(&mut contexts, &host, canvas_id, &records, &[]).unwrap();+ assert_eq!(+ take_calls(),+ [+ "host.make_current",+ "glGenBuffers(1, \"ptr\")",+ "glGenBuffers(1, \"ptr\")",+ "glBindBuffer(34962, 2)",+ "glDeleteBuffers(2, \"ptr\")",+ "glBindBuffer(34962, 0)",+ ]+ );+}++#[test]+fn creating_objects_needs_as_many_ids_as_it_creates() {+ let host = FakeHost::default();+ let (mut contexts, canvas_id) = contexts_with_one(&host, false);+ assert_eq!(+ replay(&mut contexts, &host, canvas_id, &[gen_buffers(&ids(&[1, 2]), 3)], &[]),+ Err(ReplayError("GenBuffers has another number of objects than it creates"))+ );+ assert_eq!(+ replay(&mut contexts, &host, canvas_id, &[gen_buffers(&ids(&[0]), 1)], &[]),+ Err(ReplayError("WebGL object id 0 is reserved"))+ );+}++#[test]+fn the_object_id_0_of_a_framebuffer_is_the_drawing_buffer() {+ let host = FakeHost::default();+ let (mut contexts, canvas_id) = contexts_with_one(&host, false);+ let bind_default_framebuffer = record_of(+ &commands::BindFramebuffer {+ target: GL_FRAMEBUFFER,+ framebuffer: 0,+ },+ InlineData::NONE,+ );+ let resize = record_of(+ &commands::SetDrawingBufferSize { width: 10, height: 20 },+ InlineData::NONE,+ );+ let records = [bind_default_framebuffer.clone(), resize, bind_default_framebuffer];+ replay(&mut contexts, &host, canvas_id, &records[..1], &[]).unwrap();+ host.defaults.set(super::host::DefaultBuffers {+ framebuffer: 101,+ renderbuffer: 201,+ });+ replay(&mut contexts, &host, canvas_id, &records[1..], &[]).unwrap();+ assert_eq!(+ take_calls(),+ [+ "host.make_current",+ "glBindFramebuffer(36160, 100)",+ "host.make_current",+ "host.set_size(10x20)",+ "host.make_current",+ "glBindFramebuffer(36160, 101)",+ ]+ );+ let too_big = record_of(+ &commands::SetDrawingBufferSize {+ width: 16385,+ height: 1,+ },+ InlineData::NONE,+ );+ assert_eq!(+ replay(&mut contexts, &host, canvas_id, &[too_big], &[]),+ Err(ReplayError("WebGL drawing buffer size is out of range"))+ );+}++#[test]+fn data_has_the_size_that_its_arguments_give() {+ let host = FakeHost::default();+ let (mut contexts, canvas_id) = contexts_with_one(&host, false);+ let values = [1.0_f32, 2.0];+ let bytes: Vec<u8> = values.iter().flat_map(|value| value.to_ne_bytes()).collect();+ let data = InlineData::Bytes(&bytes);+ let uniform = |count| {+ record_of(+ &commands::Uniform2fv {+ location: 3,+ count,+ value: DataSpan::following::<commands::Uniform2fv>(data),+ },+ data,+ )+ };+ replay(&mut contexts, &host, canvas_id, &[uniform(1)], &[]).unwrap();+ assert_eq!(+ replay(&mut contexts, &host, canvas_id, &[uniform(2)], &[]),+ Err(ReplayError(+ "the data of Uniform2fv.value has another size than its arguments give"+ ))+ );+ assert!(replay(&mut contexts, &host, canvas_id, &[uniform(-1)], &[]).is_err());+}++#[test]+fn data_that_may_be_null_is_either_there_or_empty() {+ let host = FakeHost::default();+ let (mut contexts, canvas_id) = contexts_with_one(&host, false);+ let buffer_data = |has_data, size, span: DataSpan, data| {+ record_of(+ &commands::BufferData {+ target: GL_ARRAY_BUFFER,+ size,+ has_data,+ data: span,+ usage: GL_STATIC_DRAW,+ ..commands::BufferData::ZEROED+ },+ data,+ )+ };+ take_calls();+ replay(+ &mut contexts,+ &host,+ canvas_id,+ &[buffer_data(false, 64, DataSpan::EMPTY, InlineData::NONE)],+ &[],+ )+ .unwrap();+ assert_eq!(take_calls()[1], "glBufferData(34962, 64, \"null\", 35044)");+ let bytes = [9_u8; 4];+ let data = InlineData::Bytes(&bytes);+ replay(+ &mut contexts,+ &host,+ canvas_id,+ &[buffer_data(+ true,+ 4,+ DataSpan::following::<commands::BufferData>(data),+ data,+ )],+ &[],+ )+ .unwrap();+ assert_eq!(take_calls()[1], "glBufferData(34962, 4, \"ptr\", 35044)");+ assert_eq!(+ replay(+ &mut contexts,+ &host,+ canvas_id,+ &[buffer_data(+ false,+ 4,+ DataSpan::following::<commands::BufferData>(data),+ data+ )],+ &[],+ ),+ Err(ReplayError("BufferData.data has data although it has none"))+ );+}++#[test]+fn a_record_whose_booleans_or_spans_are_out_of_range_is_rejected() {+ let host = FakeHost::default();+ let (mut contexts, canvas_id) = contexts_with_one(&host, false);+ let mut record = record_of(+ &commands::BufferData {+ target: GL_ARRAY_BUFFER,+ has_data: false,+ ..commands::BufferData::ZEROED+ },+ InlineData::NONE,+ );+ record[8 + 16] = 2;+ assert_eq!(+ replay(&mut contexts, &host, canvas_id, &[record], &[]),+ Err(ReplayError("WebGL payload does not hold its struct"))+ );+ let name = record_of(+ &commands::RequestExtensionANGLE {+ name: DataSpan { offset: 16, size: 64 },+ },+ InlineData::NONE,+ );+ assert_eq!(+ replay(&mut contexts, &host, canvas_id, &[name], &[]),+ Err(ReplayError("WebGL data span lies outside its payload"))+ );+ let mut truncated = record_of(&commands::Enable { cap: 1 }, InlineData::NONE);+ truncated.truncate(7);+ assert_eq!(+ replay(&mut contexts, &host, canvas_id, &[truncated], &[]),+ Err(ReplayError("Truncated WebGL command header"))+ );+}++#[test]+fn a_string_ends_with_a_nul_and_a_shader_source_is_passed_with_its_length() {+ let host = FakeHost::default();+ let (mut contexts, canvas_id) = contexts_with_one(&host, false);+ let source = InlineData::NulTerminated(b"void main() {}");+ let shader_source = record_of(+ &commands::ShaderSource {+ shader: 0,+ source: DataSpan::following::<commands::ShaderSource>(source),+ },+ source,+ );+ replay(&mut contexts, &host, canvas_id, &[shader_source], &[]).unwrap();+ assert_eq!(take_calls()[1], "glShaderSource(0, 1, \"ptr\", \"ptr\")");++ let unterminated = InlineData::Bytes(b"main");+ let shader_source = record_of(+ &commands::ShaderSource {+ shader: 0,+ source: DataSpan::following::<commands::ShaderSource>(unterminated),+ },+ unterminated,+ );+ assert_eq!(+ replay(&mut contexts, &host, canvas_id, &[shader_source], &[]),+ Err(ReplayError("WebGL string is not NUL-terminated"))+ );++ let varyings = InlineData::Bytes(b"a\0b");+ let transform_feedback_varyings = record_of(+ &commands::TransformFeedbackVaryings {+ program: 0,+ count: 2,+ varyings: DataSpan::following::<commands::TransformFeedbackVaryings>(varyings),+ buffer_mode: 0,+ },+ varyings,+ );+ assert_eq!(+ replay(&mut contexts, &host, canvas_id, &[transform_feedback_varyings], &[]),+ Err(ReplayError("WebGL string is not NUL-terminated"))+ );+}++fn sync_call<R: libcompositing_rust::webgl::wire::SyncRequest>(+ contexts: &mut WebGLContexts,+ host: &FakeHost,+ canvas_id: CanvasId,+ request: &R,+ data: InlineData<'_>,+) -> Result<Vec<u8>, ReplayError> {+ let mut bytes = Vec::new();+ assert!(encode_sync_request(&mut bytes, request, data));+ contexts.execute_sync_call(host, CLIENT, canvas_id, &bytes)+}++#[test]+fn a_page_never_blocks_the_compositor_on_a_sync_object() {+ let host = FakeHost::default();+ let (mut contexts, canvas_id) = contexts_with_one(&host, true);+ let fence = record_of(+ &commands::FenceSync {+ id: 5,+ condition: GL_SYNC_GPU_COMMANDS_COMPLETE,+ flags: 0,+ },+ InlineData::NONE,+ );+ replay(&mut contexts, &host, canvas_id, &[fence], &[]).unwrap();+ sync_call(+ &mut contexts,+ &host,+ canvas_id,+ &sync_calls::ClientWaitSyncRequest {+ sync: 5,+ flags: 1,+ timeout: 1_000_000,+ ..sync_calls::ClientWaitSyncRequest::ZEROED+ },+ InlineData::NONE,+ )+ .unwrap();+ assert_eq!(+ take_calls(),+ [+ "host.make_current",+ "glFenceSync(37143, 0)",+ "host.make_current",+ "glClientWaitSync(\"ptr\", 1, 0)",+ ]+ );+}++#[test]+fn a_synchronous_call_answers_its_outputs_after_its_struct() {+ let host = FakeHost::default();+ let (mut contexts, canvas_id) = contexts_with_one(&host, false);+ let reply = sync_call(+ &mut contexts,+ &host,+ canvas_id,+ &sync_calls::GetShaderInfoLogRequest { shader: 0, buf_size: 5 },+ InlineData::NONE,+ )+ .unwrap();+ let decoded = sync_calls::GetShaderInfoLogReply::from_reply_bytes(&reply);+ assert_eq!(decoded.info_log, DataSpan { offset: 16, size: 5 });+ assert_eq!(resolve_data_span(&reply, decoded.info_log), [0; 5]);+ assert_eq!(reply.len(), 32);++ assert_eq!(+ sync_call(+ &mut contexts,+ &host,+ canvas_id,+ &sync_calls::GetShaderInfoLogRequest {+ shader: 0,+ buf_size: -1,+ },+ InlineData::NONE,+ ),+ Err(ReplayError("WebGL asks for a buffer of a size that it cannot have"))+ );+}++unsafe extern "system" fn errors_of_the_compositor_and_then_of_the_page() -> u32 {+ thread_local! {+ static ERRORS: core::cell::RefCell<Vec<u32>> = core::cell::RefCell::new(vec![0x0502, 0x0502, 0x0505, 0, 0x0500, 0]);+ }+ ERRORS.with_borrow_mut(|errors| if errors.is_empty() { 0 } else { errors.remove(0) })+}++#[test]+fn the_errors_of_the_compositor_are_collected_before_those_of_gl() {+ let host = FakeHost::default();+ reset();+ let mut gl = recording::functions();+ gl.get_error = errors_of_the_compositor_and_then_of_the_page;+ let mut contexts = WebGLContexts::with_gl_functions(gl);+ let canvas_id = contexts.create(&host, CLIENT, options(false)).unwrap().canvas_id;+ let (context, gl) = contexts.context_and_gl(CLIENT, canvas_id).unwrap();+ let mut replayer = super::replay::Replayer {+ gl,+ host: &host,+ client: CLIENT,+ canvas_id,+ webgl2: false,+ objects: &mut context.objects,+ stashed_errors: &mut context.stashed_errors,+ defaults: host.defaults.get(),+ image_sources: &[],+ };+ assert!(replayer.stash_errors());+ let errors: Vec<u32> = (0..4).map(|_| replayer.get_error()).collect();+ assert_eq!(errors, [0x0502, 0x0505, 0x0500, 0]);+}++fn tex_image(bitmap_index: u32, format: u32, explicit_size: Option<(i32, i32)>) -> Vec<u8> {+ record_of(+ &commands::TexImage2DFromBitmap {+ target: GL_TEXTURE_2D,+ level: 0,+ internalformat: GL_RGBA as i32,+ format,+ r#type: GL_UNSIGNED_BYTE,+ bitmap_index,+ has_explicit_destination_size: explicit_size.is_some(),+ destination_width: explicit_size.map_or(0, |size| size.0),+ destination_height: explicit_size.map_or(0, |size| size.1),+ flip_y: false,+ premultiply_alpha: false,+ ..commands::TexImage2DFromBitmap::ZEROED+ },+ InlineData::NONE,+ )+}++#[test]+fn an_image_upload_names_a_known_image_in_a_known_format() {+ let host = FakeHost::default();+ let (mut contexts, canvas_id) = contexts_with_one(&host, false);+ let image = [ImageSource::RegisteredImageFrame(ImageFrameResourceId(9))];+ assert_eq!(+ replay(&mut contexts, &host, canvas_id, &[tex_image(1, GL_RGBA, None)], &image),+ Err(ReplayError("WebGL image upload references an out-of-range bitmap"))+ );+ assert_eq!(+ replay(&mut contexts, &host, canvas_id, &[tex_image(0, GL_FLOAT, None)], &image),+ Err(ReplayError(+ "WebGL image upload has an unsupported format and type combination"+ ))+ );+ *host.conversion.borrow_mut() = Some(ImageConversionOutcome::UnknownImageFrame);+ assert_eq!(+ replay(&mut contexts, &host, canvas_id, &[tex_image(0, GL_RGBA, None)], &image),+ Err(ReplayError(+ "WebGL image upload names an image frame that is not registered"+ ))+ );+}++#[test]+fn a_converted_image_is_uploaded_with_the_unpack_state_of_packed_pixels() {+ let host = FakeHost::default();+ let (mut contexts, canvas_id) = contexts_with_one(&host, false);+ let image = [ImageSource::RegisteredImageFrame(ImageFrameResourceId(9))];+ *host.conversion.borrow_mut() = Some(ImageConversionOutcome::Converted {+ pixels: vec![0; 16],+ width: 2,+ height: 2,+ });+ replay(&mut contexts, &host, canvas_id, &[tex_image(0, GL_RGBA, None)], &image).unwrap();+ assert_eq!(+ take_calls(),+ [+ "host.make_current",+ "host.convert(RegisteredImageFrame(ImageFrameResourceId(9)), RGBA8888)",+ "glGetIntegerv(3317, \"ptr\")",+ "glPixelStorei(3317, 1)",+ "glGetString(7939)",+ "glTexImage2DRobustANGLE(3553, 0, 6408, 2, 2, 0, 6408, 5121, 16, \"ptr\")",+ "glPixelStorei(3317, 0)",+ ]+ );++ replay(+ &mut contexts,+ &host,+ canvas_id,+ &[tex_image(0, GL_RGBA, Some((-1, 2)))],+ &image,+ )+ .unwrap();+ assert_eq!(+ take_calls()[4],+ "glTexImage2DRobustANGLE(3553, 0, 6408, -1, 2, 0, 6408, 5121, 0, \"ptr\")"+ );+}++#[test]+fn a_held_video_frame_is_copied_on_the_gpu_where_it_can_be() {+ let host = FakeHost::default();+ let (mut contexts, canvas_id) = contexts_with_one(&host, false);+ let video = [ImageSource::HeldVideoFrame {+ sink_handle: VideoSinkHandle(4),+ generation: 2,+ }];+ host.can_copy_images_into_textures.set(true);+ host.held_video_frame_size.set(Some(IntSize { width: 8, height: 6 }));+ replay(&mut contexts, &host, canvas_id, &[tex_image(0, GL_RGBA, None)], &video).unwrap();+ assert_eq!(+ take_calls(),+ [+ "host.make_current",+ "host.held_video_frame(4, 2)",+ "host.can_copy",+ "host.video_frame_image(4)",+ "glGetError()",+ "glGetString(7939)",+ "glTexImage2DRobustANGLE(3553, 0, 6408, 8, 6, 0, 6408, 5121, 0, \"null\")",+ "glGetError()",+ "host.copy(4, 8x6)",+ "glGetError()",+ ]+ );++ host.copy_succeeds.set(false);+ *host.conversion.borrow_mut() = Some(ImageConversionOutcome::Failed);+ replay(&mut contexts, &host, canvas_id, &[tex_image(0, GL_RGBA, None)], &video).unwrap();+ let calls = take_calls();+ assert_eq!(calls[8], "host.copy(4, 8x6)");+ assert_eq!(+ calls[9],+ "host.convert(HeldVideoFrame { sink_handle: VideoSinkHandle(4), generation: 2 }, RGBA8888)"+ );+ assert_eq!(calls.len(), 10);+}++#[test]+fn a_drawing_buffer_that_is_not_preserved_is_cleared_before_the_next_frame() {+ let host = FakeHost::default();+ let (mut contexts, canvas_id) = contexts_with_one(&host, false);+ contexts.present(&host, CLIENT, canvas_id, false).unwrap();+ let pixels = TestMemory::new(&[0; 16]);+ let rect = IntRect {+ x: 0,+ y: 0,+ width: 2,+ height: 2,+ };+ contexts+ .read_back_drawing_buffer(&host, CLIENT, canvas_id, rect, Some(&pixels))+ .unwrap();+ contexts.present(&host, CLIENT, canvas_id, false).unwrap();+ replay(+ &mut contexts,+ &host,+ canvas_id,+ &[record_of(&commands::Flush::ZEROED, InlineData::NONE)],+ &[],+ )+ .unwrap();+ contexts+ .read_back_drawing_buffer(&host, CLIENT, canvas_id, rect, Some(&pixels))+ .unwrap();+ let calls = take_calls();+ assert_eq!(+ calls[..4],+ [+ "host.present(false, false)",+ "host.read_back(true)",+ "host.present(false, true)",+ "host.make_current",+ ]+ );+ assert_eq!(calls[4], "glGetIntegerv(36006, \"ptr\")");+ assert!(calls.contains(&"glClear(17664)".to_string()));+ assert_eq!(calls[calls.len() - 2], "glFlush()");+ assert_eq!(calls[calls.len() - 1], "host.read_back(false)");+}++#[test]+fn published_commands_lie_inside_the_shared_command_buffer() {+ let host = FakeHost::default();+ let (mut contexts, canvas_id) = contexts_with_one(&host, false);+ let enable = record_of(&commands::Enable { cap: 1 }, InlineData::NONE);+ let mut shared = vec![0_u8; SHARED_DATA_REGION_OFFSET + 64];+ shared[SHARED_DATA_REGION_OFFSET..SHARED_DATA_REGION_OFFSET + enable.len()].copy_from_slice(&enable);+ let shared = Box::new(TestMemory::new(&shared));+ let shared_bytes = shared.bytes().as_ptr();+ assert_eq!(+ contexts.execute_commands_from_shared_buffer(&host, CLIENT, canvas_id, 0, 16, 1, &[]),+ Err(ReplayError(+ "WebContent published WebGL commands without a shared command buffer"+ ))+ );+ contexts.set_command_buffer(CLIENT, canvas_id, Some(shared)).unwrap();+ contexts+ .execute_commands_from_shared_buffer(&host, CLIENT, canvas_id, 0, enable.len() as u64, 42, &[])+ .unwrap();+ // SAFETY: The test owns the memory, which the context holds.+ let executed = unsafe { shared_bytes.cast::<u64>().read() };+ assert_eq!(executed, 42);+ assert_eq!(take_calls()[1], "glEnable(1)");+ for (offset, size) in [(8, 16), (0, 65), (80, 0)] {+ assert_eq!(+ contexts.execute_commands_from_shared_buffer(&host, CLIENT, canvas_id, offset, size, 43, &[]),+ Err(ReplayError(+ "WebContent published an invalid WebGL shared command buffer range"+ ))+ );+ }+ assert_eq!(+ contexts.set_command_buffer(CLIENT, canvas_id, Some(Box::new(TestMemory::new(&[0; 128])))),+ Err(ReplayError("WebContent sent an invalid WebGL shared command buffer"))+ );+}++#[test]+fn a_context_is_named_by_its_client_and_canvas() {+ let host = FakeHost::default();+ let (mut contexts, canvas_id) = contexts_with_one(&host, false);+ let other_client = WebContentClientId(8);+ assert_eq!(+ contexts.present(&host, other_client, canvas_id, true),+ Err(ReplayError("WebContent named a WebGL context that it has not created"))+ );+ contexts.clear_drawing_buffer(&host, other_client, canvas_id);+ assert!(take_calls().is_empty());+ let pixels = TestMemory::new(&[0; 4]);+ let rect = IntRect {+ x: 0,+ y: 0,+ width: 1,+ height: 1,+ };+ assert_eq!(+ contexts+ .read_pixels(+ &host,+ CLIENT,+ canvas_id,+ rect,+ GL_RGBA,+ GL_UNSIGNED_BYTE,+ 5,+ Some(&pixels)+ )+ .err(),+ Some(ReplayError("WebContent sent an invalid WebGL readPixels buffer"))+ );+ contexts.forget_client(CLIENT);+ assert!(contexts.present(&host, CLIENT, canvas_id, true).is_err());+ contexts.destroy(&host, CLIENT, canvas_id);+ record("end".into());+ assert_eq!(take_calls(), ["end"]);+}