Truly independent web browser
LibCompositing+LibWeb: Move the WebGL wire vocabulary to LibCompositing
Aliaksandr Kalenik5b1fde0fdd14
diff --git a/Cargo.lock b/Cargo.lockindex ccf51564929..ee6424b66be 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1856,6 +1856,7 @@ dependencies = ["libgfx_rust","libipc_rust","rustc-demangle",+ "serde_json",][[package]]diff --git a/Libraries/LibCompositing/Rust/Cargo.toml b/Libraries/LibCompositing/Rust/Cargo.tomlindex 931ae3dfaad..6ab2df9acc9 100644--- a/Libraries/LibCompositing/Rust/Cargo.toml+++ b/Libraries/LibCompositing/Rust/Cargo.toml@@ -20,6 +20,10 @@ rustc-demangle = "0.1"[build-dependencies]cbindgen = "0.29"+serde_json = { version = "1", features = ["float_roundtrip", "preserve_order"] }++[dev-dependencies]+serde_json = { version = "1", features = ["float_roundtrip", "preserve_order"] }[lints]workspace = truediff --git a/Libraries/LibCompositing/Rust/build.rs b/Libraries/LibCompositing/Rust/build.rsindex 1e6d3c4089d..e47f9ac50ba 100644--- a/Libraries/LibCompositing/Rust/build.rs+++ b/Libraries/LibCompositing/Rust/build.rs@@ -9,6 +9,13 @@ use std::error::Error;use std::path::{Path, PathBuf};use std::process::Command;+#[path = "generate/webgl_wire.rs"]+mod webgl_wire;++#[allow(dead_code, reason = "the model is for the generators of the other crates as well")]+#[path = "generate/webgl_wire_model.rs"]+mod webgl_wire_model;+// AK::Optional is not trivial for calls under every C++ ABI: Apple clang returns it through memory, where Rust// returns the matching #[repr(C)] struct in registers. Keep it out of extern "C" signatures; pass a plain// #[repr(C)] struct and convert it to an Optional on the C++ side.@@ -349,11 +356,29 @@ fn generate_ipc_definitions(manifest_dir: &Path, out_dir: &Path) -> Result<(), BOk(())}+/// The vocabulary of the WebGL command stream, which src/webgl/vocabulary.rs includes.+fn generate_webgl_wire_vocabulary(manifest_dir: &Path, out_dir: &Path) -> Result<(), Box<dyn Error>> {+ let functions_path = manifest_dir.join("../WebGL/GLFunctions.json");+ println!("cargo:rerun-if-changed={}", functions_path.display());+ println!("cargo:rerun-if-changed=generate");+ let json = std::fs::read_to_string(&functions_path)?;+ let generate = |json: &str| -> Result<String, String> {+ let functions = webgl_wire_model::parse_functions(json)?;+ Ok(webgl_wire::write_wire_vocabulary(&webgl_wire_model::vocabulary(+ &functions,+ )?))+ };+ let vocabulary = generate(&json).map_err(|error| format!("{}: {error}", functions_path.display()))?;+ std::fs::write(out_dir.join("webgl_wire.rs"), vocabulary)?;+ 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_ipc_definitions(&manifest_dir, &out_dir)?;+ generate_webgl_wire_vocabulary(&manifest_dir, &out_dir)?;println!("cargo:rerun-if-changed=build.rs");println!("cargo:rerun-if-changed=cbindgen.toml");diff --git a/Libraries/LibWeb/Bindings/Rust/generate/webgl_wire.rs b/Libraries/LibCompositing/Rust/generate/webgl_wire.rssimilarity index 89%rename from Libraries/LibWeb/Bindings/Rust/generate/webgl_wire.rsrename to Libraries/LibCompositing/Rust/generate/webgl_wire.rsindex dbc06312468..021d492901c 100644--- a/Libraries/LibWeb/Bindings/Rust/generate/webgl_wire.rs+++ b/Libraries/LibCompositing/Rust/generate/webgl_wire.rs@@ -5,7 +5,7 @@*///! Writes the vocabulary of the WebGL command stream: the command types, the synchronous call types and the struct of-//! each, which src/web_gl/proxy/vocabulary.rs includes. The C++ side of the stream gets the same from+//! each, which src/webgl/vocabulary.rs includes. The C++ side of the stream gets the same from//! Meta/Generators/generate_libweb_webgl_commands.py.use std::fmt::Write;@@ -60,9 +60,9 @@ fn write_struct(out: &mut String, rust_name: &str, layout: &WireStruct) {let fields = rust_fields(layout);writeln!(out, " /// `{}`", layout.cpp_name).unwrap();out.push_str(" #[derive(Clone, Copy, Debug, PartialEq)]\n #[repr(C)]\n");- writeln!(out, " pub(crate) struct {rust_name} {{").unwrap();+ writeln!(out, " pub struct {rust_name} {{").unwrap();for field in &fields {- writeln!(out, " pub(crate) {}: {},", field.name, field.rust_type).unwrap();+ writeln!(out, " pub {}: {},", field.name, field.rust_type).unwrap();}out.push_str(" }\n");// NB: The assertions below are what the safety of the implementation rests on: the fields are where the C ABI@@ -97,18 +97,13 @@ fn write_struct(out: &mut String, rust_name: &str, layout: &WireStruct) {fn write_type_enum(out: &mut String, enum_name: &str, count_name: &str, description: &str, names: &[&str]) {writeln!(out, "/// {description}").unwrap();out.push_str("#[derive(Clone, Copy, Debug, PartialEq, Eq)]\n#[repr(u16)]\n");- writeln!(out, "pub(crate) enum {enum_name} {{").unwrap();+ writeln!(out, "pub enum {enum_name} {{").unwrap();for name in names {writeln!(out, " {name},").unwrap();}out.push_str("}\n\n");// NB: Only the tests of the vocabulary ask how many types there are.- writeln!(- out,- "#[cfg(test)]\npub(crate) const {count_name}: u16 = {};\n",- names.len()- )- .unwrap();+ writeln!(out, "#[cfg(test)]\npub const {count_name}: u16 = {};\n", names.len()).unwrap();}fn write_layout_words(out: &mut String, rust_path: &str, layout: &WireStruct) {@@ -136,7 +131,7 @@ fn write_layout_words(out: &mut String, rust_path: &str, layout: &WireStruct) {pub fn write_wire_vocabulary(vocabulary: &Vocabulary) -> String {let mut out = String::from("// Generated by build.rs from Libraries/LibCompositing/WebGL/GLFunctions.json.\n\n");out.push_str("use core::mem::offset_of;\n\n");- out.push_str("use crate::web_gl::proxy::wire::DataSpan;\n\n");+ out.push_str("use crate::webgl::wire::DataSpan;\n\n");let command_names: Vec<&str> = vocabulary.commands@@ -171,17 +166,17 @@ pub fn write_wire_vocabulary(vocabulary: &Vocabulary) -> String {out.push_str("/// The size of the largest struct of a record.\n");writeln!(out,- "pub(crate) const MAX_COMMAND_STRUCT_SIZE: usize = {max_command_struct_size};\n"+ "pub const MAX_COMMAND_STRUCT_SIZE: usize = {max_command_struct_size};\n").unwrap();out.push_str("/// The structs of the records of the command stream, which are those of the C++ namespace `Commands`.\n",);- out.push_str("pub(crate) mod commands {\n");+ out.push_str("pub mod commands {\n");out.push_str(" use core::mem::offset_of;\n\n");out.push_str(" use super::CommandType;\n");- out.push_str(" use crate::web_gl::proxy::wire::{Command, DataSpan, WireStruct};\n\n");+ out.push_str(" use crate::webgl::wire::{Command, DataSpan, WireStruct};\n\n");for entry in &vocabulary.commands {let name = entry.function.command_name();write_struct(&mut out, name, &entry.layout);@@ -192,10 +187,10 @@ pub fn write_wire_vocabulary(vocabulary: &Vocabulary) -> String {out.push_str("}\n\n");out.push_str("/// The structs of the synchronous calls, which are those of the C++ namespace `SyncCalls`.\n");- out.push_str("pub(crate) mod sync_calls {\n");+ out.push_str("pub mod sync_calls {\n");out.push_str(" use core::mem::offset_of;\n\n");out.push_str(" use super::SyncCallType;\n");- out.push_str(" use crate::web_gl::proxy::wire::{DataSpan, SyncReply, SyncRequest, WireStruct};\n\n");+ out.push_str(" use crate::webgl::wire::{DataSpan, SyncReply, SyncRequest, WireStruct};\n\n");for entry in &vocabulary.sync_calls {let name = entry.function.command_name();write_struct(&mut out, &format!("{name}Request"), &entry.request);@@ -216,7 +211,7 @@ pub fn write_wire_vocabulary(vocabulary: &Vocabulary) -> String {/// per field the hash of its name, the hash of the name of its C++ type, its offset and its size.\n",);out.push_str("#[allow(clippy::unreadable_literal, reason = \"the hashes are not read\")]\n");- out.push_str("pub(crate) static WIRE_STRUCT_LAYOUTS: &[u32] = &[\n");+ out.push_str("pub static WIRE_STRUCT_LAYOUTS: &[u32] = &[\n");for entry in &vocabulary.commands {write_layout_words(&mut out,diff --git a/Libraries/LibWeb/Bindings/Rust/generate/webgl_wire_model.rs b/Libraries/LibCompositing/Rust/generate/webgl_wire_model.rssimilarity index 76%rename from Libraries/LibWeb/Bindings/Rust/generate/webgl_wire_model.rsrename to Libraries/LibCompositing/Rust/generate/webgl_wire_model.rsindex 9822df85939..7db8c3d7704 100644--- a/Libraries/LibWeb/Bindings/Rust/generate/webgl_wire_model.rs+++ b/Libraries/LibCompositing/Rust/generate/webgl_wire_model.rs@@ -588,162 +588,3 @@ pub fn wire_layout_name_hash(name: &str) -> u32 {(hash ^ u32::from(byte)).wrapping_mul(0x0100_0193)})}--#[cfg(test)]-mod tests {- use super::*;-- fn fields(types_and_names: &[(&str, &str)]) -> Vec<FieldSpec> {- types_and_names- .iter()- .map(|(cpp_type, name)| FieldSpec {- cpp_type: (*cpp_type).into(),- name: (*name).into(),- argument: None,- })- .collect()- }-- #[test]- fn a_struct_is_laid_out_as_the_c_abi_does() {- let layout = wire_struct(- "Commands::Example".into(),- fields(&[- ("GLenum", "target"),- ("GLintptr", "offset"),- ("GLboolean", "flag"),- ("WebGLDataSpan", "data"),- ]),- )- .unwrap();- let offsets: Vec<usize> = layout.fields.iter().map(|field| field.offset).collect();- assert_eq!(offsets, [0, 8, 16, 20]);- assert_eq!((layout.size, layout.alignment), (32, 8));- }-- #[test]- fn a_struct_without_fields_is_one_byte() {- let layout = wire_struct("SyncCalls::Finish::Request".into(), Vec::new()).unwrap();- assert_eq!((layout.size, layout.alignment), (1, 1));- }-- #[test]- fn a_field_of_an_unknown_type_is_rejected() {- let error = wire_struct("Commands::Example".into(), fields(&[("GLdouble", "depth")])).unwrap_err();- assert!(- error.contains("Commands::Example.depth has the type GLdouble"),- "{error}"- );- }-- #[test]- fn names_are_converted_as_the_cpp_generators_convert_them() {- for (name, snake_case) in [- ("ActiveTexture", "active_texture"),- ("TexImage3DRobustANGLE", "tex_image3d_robust_angle"),- ("GetInteger64vRobustANGLE", "get_integer64v_robust_angle"),- ("UniformMatrix4fv", "uniform_matrix4fv"),- ("bufSize", "buf_size"),- ("srcX0", "src_x0"),- ("uniformBlockName", "uniform_block_name"),- ] {- assert_eq!(title_case_to_snake_case(name), snake_case);- }- }-- #[test]- fn the_structs_of_a_function_follow_from_its_signature() {- let functions = parse_functions(- r#"[- {"name": "glBufferData", "return": "void", "category": "command", "args": [- {"type": "GLenum", "name": "target"},- {"type": "GLsizeiptr", "name": "size"},- {"type": "void const*", "name": "data", "payload": "size", "nullable": true},- {"type": "GLenum", "name": "usage"}]},- {"name": "glGetActiveAttrib", "return": "void", "category": "sync", "args": [- {"type": "GLuint", "name": "program", "object": true},- {"type": "GLsizei", "name": "bufSize"},- {"type": "GLsizei*", "name": "length", "out": true},- {"type": "GLchar*", "name": "name", "out": true, "payload": "bufSize * sizeof(GLchar)"}]},- {"name": "glCreateShader", "return": "GLuint", "category": "gen", "args": [- {"type": "GLenum", "name": "type"}]}- ]"#,- )- .unwrap();- let vocabulary = vocabulary(&functions).unwrap();- let described = |layout: &WireStruct| -> Vec<String> {- layout- .fields- .iter()- .map(|field| format!("{} {} @{}", field.spec.cpp_type, field.spec.name, field.offset))- .collect()- };- assert_eq!(vocabulary.commands[0].layout.cpp_name, "Commands::BufferData");- assert_eq!(- described(&vocabulary.commands[0].layout),- [- "GLenum target @0",- "GLsizeiptr size @8",- "bool has_data @16",- "WebGLDataSpan data @20",- "GLenum usage @28"- ]- );- assert_eq!(- described(&vocabulary.commands[1].layout),- ["WebGLObjectId id @0", "GLenum type @4"]- );- assert_eq!(- vocabulary.sync_calls[0].request.cpp_name,- "SyncCalls::GetActiveAttrib::Request"- );- assert_eq!(- described(&vocabulary.sync_calls[0].request),- ["WebGLObjectId program @0", "GLsizei buf_size @4"]- );- assert_eq!(- described(&vocabulary.sync_calls[0].reply),- ["GLsizei length @0", "WebGLDataSpan name @4"]- );- }-- #[test]- fn what_the_model_does_not_know_is_rejected() {- let unknown_function_key =- r#"[{"name": "glFlush", "return": "void", "category": "command", "args": [], "flushes": true}]"#;- assert!(- parse_functions(unknown_function_key)- .unwrap_err()- .contains("glFlush has the key \"flushes\"")- );- let unknown_argument_key = r#"[{"name": "glEnable", "return": "void", "category": "command", "args": [- {"type": "GLenum", "name": "cap", "validated": true}]}]"#;- assert!(- parse_functions(unknown_argument_key)- .unwrap_err()- .contains("has the key \"validated\"")- );- let unknown_category = r#"[{"name": "glFlush", "return": "void", "category": "deferred", "args": []}]"#;- assert!(- parse_functions(unknown_category)- .unwrap_err()- .contains("has the category \"deferred\"")- );- let unhandled_pointer = r#"[{"name": "glGetPointerv", "return": "void", "category": "command", "args": [- {"type": "void**", "name": "params"}]}]"#;- let functions = parse_functions(unhandled_pointer).unwrap();- assert!(- vocabulary(&functions)- .err()- .unwrap()- .contains("does not handle the pointer argument params")- );- }-- #[test]- fn a_name_hash_is_fnv_1a() {- assert_eq!(wire_layout_name_hash(""), 0x811C_9DC5);- assert_eq!(wire_layout_name_hash("a"), 0xE40C_292C);- assert_eq!(wire_layout_name_hash("Commands::ActiveTexture"), 0x9B0F_0F7C);- }-}diff --git a/Libraries/LibCompositing/Rust/generate/webgl_wire_model_tests.rs b/Libraries/LibCompositing/Rust/generate/webgl_wire_model_tests.rsnew file mode 100644index 00000000000..8fc103f6e11--- /dev/null+++ b/Libraries/LibCompositing/Rust/generate/webgl_wire_model_tests.rs@@ -0,0 +1,164 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The tests of the model of the WebGL functions, which run with those of libcompositing_rust only, as every crate+//! whose build script generates from the model includes it.++use crate::webgl_wire_model::*;++fn fields(types_and_names: &[(&str, &str)]) -> Vec<FieldSpec> {+ types_and_names+ .iter()+ .map(|(cpp_type, name)| FieldSpec {+ cpp_type: (*cpp_type).into(),+ name: (*name).into(),+ argument: None,+ })+ .collect()+}++#[test]+fn a_struct_is_laid_out_as_the_c_abi_does() {+ let layout = wire_struct(+ "Commands::Example".into(),+ fields(&[+ ("GLenum", "target"),+ ("GLintptr", "offset"),+ ("GLboolean", "flag"),+ ("WebGLDataSpan", "data"),+ ]),+ )+ .unwrap();+ let offsets: Vec<usize> = layout.fields.iter().map(|field| field.offset).collect();+ assert_eq!(offsets, [0, 8, 16, 20]);+ assert_eq!((layout.size, layout.alignment), (32, 8));+}++#[test]+fn a_struct_without_fields_is_one_byte() {+ let layout = wire_struct("SyncCalls::Finish::Request".into(), Vec::new()).unwrap();+ assert_eq!((layout.size, layout.alignment), (1, 1));+}++#[test]+fn a_field_of_an_unknown_type_is_rejected() {+ let error = wire_struct("Commands::Example".into(), fields(&[("GLdouble", "depth")])).unwrap_err();+ assert!(+ error.contains("Commands::Example.depth has the type GLdouble"),+ "{error}"+ );+}++#[test]+fn names_are_converted_as_the_cpp_generators_convert_them() {+ for (name, snake_case) in [+ ("ActiveTexture", "active_texture"),+ ("TexImage3DRobustANGLE", "tex_image3d_robust_angle"),+ ("GetInteger64vRobustANGLE", "get_integer64v_robust_angle"),+ ("UniformMatrix4fv", "uniform_matrix4fv"),+ ("bufSize", "buf_size"),+ ("srcX0", "src_x0"),+ ("uniformBlockName", "uniform_block_name"),+ ] {+ assert_eq!(title_case_to_snake_case(name), snake_case);+ }+}++#[test]+fn the_structs_of_a_function_follow_from_its_signature() {+ let functions = parse_functions(+ r#"[+ {"name": "glBufferData", "return": "void", "category": "command", "args": [+ {"type": "GLenum", "name": "target"},+ {"type": "GLsizeiptr", "name": "size"},+ {"type": "void const*", "name": "data", "payload": "size", "nullable": true},+ {"type": "GLenum", "name": "usage"}]},+ {"name": "glGetActiveAttrib", "return": "void", "category": "sync", "args": [+ {"type": "GLuint", "name": "program", "object": true},+ {"type": "GLsizei", "name": "bufSize"},+ {"type": "GLsizei*", "name": "length", "out": true},+ {"type": "GLchar*", "name": "name", "out": true, "payload": "bufSize * sizeof(GLchar)"}]},+ {"name": "glCreateShader", "return": "GLuint", "category": "gen", "args": [+ {"type": "GLenum", "name": "type"}]}+ ]"#,+ )+ .unwrap();+ let vocabulary = vocabulary(&functions).unwrap();+ let described = |layout: &WireStruct| -> Vec<String> {+ layout+ .fields+ .iter()+ .map(|field| format!("{} {} @{}", field.spec.cpp_type, field.spec.name, field.offset))+ .collect()+ };+ assert_eq!(vocabulary.commands[0].layout.cpp_name, "Commands::BufferData");+ assert_eq!(+ described(&vocabulary.commands[0].layout),+ [+ "GLenum target @0",+ "GLsizeiptr size @8",+ "bool has_data @16",+ "WebGLDataSpan data @20",+ "GLenum usage @28"+ ]+ );+ assert_eq!(+ described(&vocabulary.commands[1].layout),+ ["WebGLObjectId id @0", "GLenum type @4"]+ );+ assert_eq!(+ vocabulary.sync_calls[0].request.cpp_name,+ "SyncCalls::GetActiveAttrib::Request"+ );+ assert_eq!(+ described(&vocabulary.sync_calls[0].request),+ ["WebGLObjectId program @0", "GLsizei buf_size @4"]+ );+ assert_eq!(+ described(&vocabulary.sync_calls[0].reply),+ ["GLsizei length @0", "WebGLDataSpan name @4"]+ );+}++#[test]+fn what_the_model_does_not_know_is_rejected() {+ let unknown_function_key =+ r#"[{"name": "glFlush", "return": "void", "category": "command", "args": [], "flushes": true}]"#;+ assert!(+ parse_functions(unknown_function_key)+ .unwrap_err()+ .contains("glFlush has the key \"flushes\"")+ );+ let unknown_argument_key = r#"[{"name": "glEnable", "return": "void", "category": "command", "args": [+ {"type": "GLenum", "name": "cap", "validated": true}]}]"#;+ assert!(+ parse_functions(unknown_argument_key)+ .unwrap_err()+ .contains("has the key \"validated\"")+ );+ let unknown_category = r#"[{"name": "glFlush", "return": "void", "category": "deferred", "args": []}]"#;+ assert!(+ parse_functions(unknown_category)+ .unwrap_err()+ .contains("has the category \"deferred\"")+ );+ let unhandled_pointer = r#"[{"name": "glGetPointerv", "return": "void", "category": "command", "args": [+ {"type": "void**", "name": "params"}]}]"#;+ let functions = parse_functions(unhandled_pointer).unwrap();+ assert!(+ vocabulary(&functions)+ .err()+ .unwrap()+ .contains("does not handle the pointer argument params")+ );+}++#[test]+fn a_name_hash_is_fnv_1a() {+ assert_eq!(wire_layout_name_hash(""), 0x811C_9DC5);+ assert_eq!(wire_layout_name_hash("a"), 0xE40C_292C);+ assert_eq!(wire_layout_name_hash("Commands::ActiveTexture"), 0x9B0F_0F7C);+}diff --git a/Libraries/LibCompositing/Rust/src/lib.rs b/Libraries/LibCompositing/Rust/src/lib.rsindex 7ad06a79922..da25bd5a12a 100644--- a/Libraries/LibCompositing/Rust/src/lib.rs+++ b/Libraries/LibCompositing/Rust/src/lib.rs@@ -31,3 +31,17 @@ mod test_stubs;pub mod time;pub mod visual_animation;pub mod visual_context;+pub mod webgl;++// The model of the WebGL functions, which the build scripts of the crates that generate from it include, and whose tests+// run with those of this crate.+#[cfg(test)]+#[allow(+ dead_code,+ reason = "the tests do not run the generators, which the model is for as well"+)]+#[path = "../generate/webgl_wire_model.rs"]+mod webgl_wire_model;+#[cfg(test)]+#[path = "../generate/webgl_wire_model_tests.rs"]+mod webgl_wire_model_tests;diff --git a/Libraries/LibCompositing/Rust/src/webgl/mod.rs b/Libraries/LibCompositing/Rust/src/webgl/mod.rsnew file mode 100644index 00000000000..9d05fe65c4a--- /dev/null+++ b/Libraries/LibCompositing/Rust/src/webgl/mod.rs@@ -0,0 +1,16 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The WebGL command stream that WebContent records and the Compositor replays, as Libraries/LibCompositing/WebGL/+//! GLFunctions.json defines it.++pub mod vocabulary;+pub mod wire;++/// 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;+pub const DEFAULT_SHARED_DATA_REGION_CAPACITY: usize = 32 * 1024 * 1024;diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/vocabulary.rs b/Libraries/LibCompositing/Rust/src/webgl/vocabulary.rssimilarity index 98%rename from Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/vocabulary.rsrename to Libraries/LibCompositing/Rust/src/webgl/vocabulary.rsindex a17e438bb11..6f2b7537091 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/vocabulary.rs+++ b/Libraries/LibCompositing/Rust/src/webgl/vocabulary.rs@@ -12,7 +12,7 @@ include!(concat!(env!("OUT_DIR"), "/webgl_wire.rs"));#[cfg(test)]mod tests {use super::*;- use crate::web_gl::proxy::wire::{DataSpan, WireStruct};+ use crate::webgl::wire::{DataSpan, WireStruct};#[test]fn a_struct_is_its_fields_in_the_byte_order_of_the_machine() {diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/wire.rs b/Libraries/LibCompositing/Rust/src/webgl/wire.rssimilarity index 93%rename from Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/wire.rsrename to Libraries/LibCompositing/Rust/src/webgl/wire.rsindex 05c4cf01d19..cf93951a794 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/wire.rs+++ b/Libraries/LibCompositing/Rust/src/webgl/wire.rs@@ -15,25 +15,25 @@ use super::vocabulary::{CommandType, SyncCallType};/// Records start at multiples of this many bytes, and so does the data that follows a struct, counted from the start/// of the struct.-pub(crate) const RECORD_ALIGNMENT: usize = 16;+pub const RECORD_ALIGNMENT: usize = 16;/// What precedes the struct of a record and of a request: its type as a `u16`, two unused bytes, and the number of/// bytes that follow the header as a `u32`.-pub(crate) const HEADER_SIZE: usize = 8;-pub(crate) const HEADER_PAYLOAD_SIZE_OFFSET: usize = 4;+pub const HEADER_SIZE: usize = 8;+pub const HEADER_PAYLOAD_SIZE_OFFSET: usize = 4;/// `size` bytes that start `offset` bytes after the start of the struct that has the span as a field.#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]#[repr(C)]-pub(crate) struct DataSpan {- pub(crate) offset: u32,- pub(crate) size: u32,+pub struct DataSpan {+ pub offset: u32,+ pub size: u32,}impl DataSpan {- pub(crate) const EMPTY: Self = Self { offset: 0, size: 0 };+ pub const EMPTY: Self = Self { offset: 0, size: 0 };- pub(crate) fn following<S: WireStruct>(data: InlineData<'_>) -> Self {+ pub fn following<S: WireStruct>(data: InlineData<'_>) -> Self {Self {offset: const { offset_of_data_following_struct(size_of::<S>()) },// NB: Data of 4 GiB or more has no span. It has no `FramedSize` either, so the recorder refuses what it@@ -52,7 +52,7 @@ 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.-pub(crate) unsafe trait WireStruct: Copy + 'static {+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;@@ -63,11 +63,11 @@ pub(crate) unsafe trait WireStruct: Copy + 'static {}}-pub(crate) trait Command: WireStruct {+pub trait Command: WireStruct {const TYPE: CommandType;}-pub(crate) trait SyncRequest: WireStruct {+pub trait SyncRequest: WireStruct {const TYPE: SyncCallType;type Reply: SyncReply;}@@ -75,7 +75,7 @@ pub(crate) trait SyncRequest: WireStruct {/// # Safety////// Every bit pattern is a value of the type.-pub(crate) unsafe trait SyncReply: WireStruct {+pub unsafe trait SyncReply: WireStruct {fn from_reply_bytes(reply: &[u8]) -> Self {assert!(reply.len() >= size_of::<Self>(),@@ -88,7 +88,7 @@ pub(crate) unsafe trait SyncReply: WireStruct {}#[derive(Clone, Copy, Debug)]-pub(crate) enum InlineData<'a> {+pub enum InlineData<'a> {/// No bytes take no room at all, not even for the alignment of what would follow.Bytes(&'a [u8]),/// The stream has a NUL after the bytes.@@ -96,15 +96,19 @@ pub(crate) enum InlineData<'a> {}impl InlineData<'_> {- pub(crate) const NONE: Self = Self::Bytes(&[]);+ pub const NONE: Self = Self::Bytes(&[]);- pub(crate) fn len(self) -> usize {+ pub fn len(self) -> usize {match self {Self::Bytes(bytes) => bytes.len(),Self::NulTerminated(bytes) => bytes.len() + 1,}}+ pub fn is_empty(self) -> bool {+ self.len() == 0+ }+/// # Safety////// `destination` is valid for writes of `self.len()` bytes that do not overlap the data.@@ -160,7 +164,7 @@ impl FramedSize {}}-pub(crate) fn padded_record_size(struct_size: usize, inline_data_size: usize) -> Option<usize> {+pub fn padded_record_size(struct_size: usize, inline_data_size: usize) -> Option<usize> {FramedSize::of_record(struct_size, inline_data_size).map(|size| size.size_with_header)}@@ -188,7 +192,7 @@ unsafe fn write_framed(unsafe {ptr::copy_nonoverlapping(header.as_ptr(), destination, HEADER_SIZE);ptr::copy_nonoverlapping(payload.as_ptr(), destination.add(HEADER_SIZE), payload.len());- if inline_data.len() > 0 {+ if !inline_data.is_empty() {let inline_data_offset = HEADER_SIZE + payload.len().next_multiple_of(RECORD_ALIGNMENT);ptr::write_bytes(destination.add(written), 0, inline_data_offset - written);inline_data.write_to(destination.add(inline_data_offset));@@ -198,7 +202,7 @@ unsafe fn write_framed(}}-pub(crate) struct Record<'a> {+pub struct Record<'a> {command_type: CommandType,payload: &'a [u8],inline_data: InlineData<'a>,@@ -206,7 +210,7 @@ pub(crate) struct Record<'a> {}impl<'a> Record<'a> {- pub(crate) fn new(command_type: CommandType, payload: &'a [u8], inline_data: InlineData<'a>) -> Option<Self> {+ pub fn new(command_type: CommandType, payload: &'a [u8], inline_data: InlineData<'a>) -> Option<Self> {Some(Self {command_type,payload,@@ -215,14 +219,14 @@ impl<'a> Record<'a> {})}- pub(crate) fn size(&self) -> usize {+ pub fn size(&self) -> usize {self.size.size_with_header}/// # Safety////// `destination` is valid for writes of `self.size()` bytes that overlap neither the struct nor the data.- pub(crate) unsafe fn write_to(&self, destination: *mut u8) {+ pub unsafe fn write_to(&self, destination: *mut u8) {// SAFETY: The caller provides the bytes of the record, whose size is that of the struct with the data.unsafe {write_framed(@@ -235,7 +239,7 @@ impl<'a> Record<'a> {}}- pub(crate) fn append_to(&self, commands: &mut Vec<u8>) {+ pub fn append_to(&self, commands: &mut Vec<u8>) {let record_offset = commands.len();assert!(record_offset.is_multiple_of(RECORD_ALIGNMENT));commands.resize(record_offset + self.size(), 0);@@ -243,7 +247,7 @@ impl<'a> Record<'a> {unsafe { self.write_to(commands.as_mut_ptr().add(record_offset)) };}- pub(crate) fn encoded(&self) -> Vec<u8> {+ pub fn encoded(&self) -> Vec<u8> {let mut bytes = Vec::new();self.append_to(&mut bytes);bytes@@ -252,7 +256,7 @@ impl<'a> Record<'a> {/// False, with no request in `request_bytes`, when the stream cannot carry the request.#[must_use]-pub(crate) fn encode_sync_request<R: SyncRequest>(+pub fn encode_sync_request<R: SyncRequest>(request_bytes: &mut Vec<u8>,request: &R,inline_data: InlineData<'_>,@@ -275,7 +279,7 @@ pub(crate) fn encode_sync_request<R: SyncRequest>(true}-pub(crate) fn resolve_data_span(reply: &[u8], span: DataSpan) -> &[u8] {+pub fn resolve_data_span(reply: &[u8], span: DataSpan) -> &[u8] {let start = span.offset as usize;start.checked_add(span.size as usize)diff --git a/Libraries/LibWeb/Bindings/Rust/build.rs b/Libraries/LibWeb/Bindings/Rust/build.rsindex 3ec0e388120..a14b0e618eb 100644--- a/Libraries/LibWeb/Bindings/Rust/build.rs+++ b/Libraries/LibWeb/Bindings/Rust/build.rs@@ -10,9 +10,9 @@//! clippy do, leaves the bindings out and compiles the implementations without them. rustc tracks the file itself, as//! the crate includes it.//!-//! Also generates what the WebGL implementation shares with the rest of the tree: the vocabulary of the command-//! stream, the methods of its recorder and the GL constants. Those do not need the bindings, so every build of the-//! crate has them.+//! Also generates what the WebGL implementation needs from the rest of the tree: the methods of its recorder, from the+//! model of the command stream that libcompositing_rust has, and the GL constants. Those do not need the bindings, so+//! every build of the crate has them.use std::env;use std::fs;@@ -24,10 +24,8 @@ mod webgl_constants;#[path = "generate/webgl_proxy.rs"]mod webgl_proxy;-#[path = "generate/webgl_wire.rs"]-mod webgl_wire;--#[path = "generate/webgl_wire_model.rs"]+#[allow(dead_code, reason = "the model is for the generators of the other crates as well")]+#[path = "../../../LibCompositing/Rust/generate/webgl_wire_model.rs"]mod webgl_wire_model;fn read_tracked(path: &Path) -> String {@@ -36,18 +34,17 @@ fn read_tracked(path: &Path) -> String {}fn generate_webgl_command_recording(libraries: &Path, out_dir: &Path) {+ println!(+ "cargo:rerun-if-changed={}",+ libraries.join("LibCompositing/Rust/generate").display()+ );let functions_path = libraries.join("LibCompositing/WebGL/GLFunctions.json");- let generate = |json: &str| -> Result<(String, String), String> {+ let generate = |json: &str| -> Result<String, String> {let functions = webgl_wire_model::parse_functions(json)?;- let vocabulary = webgl_wire_model::vocabulary(&functions)?;- Ok((- webgl_wire::write_wire_vocabulary(&vocabulary),- webgl_proxy::write_proxy(&functions)?,- ))+ webgl_proxy::write_proxy(&functions)};- let (wire_vocabulary, proxy) = generate(&read_tracked(&functions_path))+ let proxy = generate(&read_tracked(&functions_path)).unwrap_or_else(|error| panic!("{}: {error}", functions_path.display()));- fs::write(out_dir.join("webgl_wire.rs"), wire_vocabulary).expect("write webgl_wire.rs");fs::write(out_dir.join("webgl_proxy.rs"), proxy).expect("write webgl_proxy.rs");}diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rsindex 70b69dc336d..8b552fc2c8a 100644--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs@@ -435,9 +435,9 @@ mod webgl_proxy;#[cfg(test)]#[allow(dead_code,- reason = "the tests do not run the writer of the vocabulary, which the model is for as well"+ reason = "the tests do not run the generators, which the model is for as well")]-#[path = "../generate/webgl_wire_model.rs"]+#[path = "../../../../LibCompositing/Rust/generate/webgl_wire_model.rs"]mod webgl_wire_model;// NB: Little in this crate names libweb_rust, which C++ calls into. Linking it keeps its extern "C" functions in thediff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/fingerprint.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/fingerprint.rsindex a7dc75c60fc..87999f3554a 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/fingerprint.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/fingerprint.rs@@ -12,9 +12,10 @@use std::sync::Once;-use super::proxy::recorder::{DEFAULT_SHARED_DATA_REGION_CAPACITY, SHARED_DATA_REGION_OFFSET};-use super::proxy::vocabulary::WIRE_STRUCT_LAYOUTS;-use super::proxy::wire::{HEADER_PAYLOAD_SIZE_OFFSET, HEADER_SIZE, RECORD_ALIGNMENT};+use libcompositing_rust::webgl::vocabulary::WIRE_STRUCT_LAYOUTS;+use libcompositing_rust::webgl::wire::{HEADER_PAYLOAD_SIZE_OFFSET, HEADER_SIZE, RECORD_ALIGNMENT};+use libcompositing_rust::webgl::{DEFAULT_SHARED_DATA_REGION_CAPACITY, SHARED_DATA_REGION_OFFSET};+use super::state::MAX_WEBGL_DRAWING_BUFFER_DIMENSION;/// RemoteWebGLTransportFFI.cpp has a struct of the same name, and reports the constants of the C++ side as one.@@ -67,7 +68,7 @@ pub(crate) fn verify_that_rust_and_cpp_agree_on_layouts_and_constants() {assert!(first_difference.is_none() && replayer_layouts.len() == WIRE_STRUCT_LAYOUTS.len(),"the structs of the WebGL command stream differ between its recorder and its replayer, from word \- {first_difference:?} of {} and {} layout words on; Libraries/LibWeb/Bindings/Rust/generate and \+ {first_difference:?} of {} and {} layout words on; Libraries/LibCompositing/Rust/generate and \Meta/Generators/libweb_webgl.py have to derive the same structs from GLFunctions.json",WIRE_STRUCT_LAYOUTS.len(),replayer_layouts.len()diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/custom.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/custom.rsindex 9f8b36d1fe4..fa184b7f284 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/custom.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/custom.rs@@ -10,10 +10,11 @@use std::rc::Rc;+use libcompositing_rust::webgl::vocabulary::{commands, sync_calls};+use libcompositing_rust::webgl::wire::{DataSpan, InlineData, WireStruct, resolve_data_span};+use super::recorder::{Proxy, bytes_of_mut, copy_reply_data, until_nul};use super::transport::{ReadPixelsResult, SharedMemory, Transport};-use super::vocabulary::{commands, sync_calls};-use super::wire::{DataSpan, InlineData, WireStruct, resolve_data_span};use crate::web_gl::constants::{GL_INVALID_VALUE, GL_OUT_OF_MEMORY};fn pack_strings(strings: &[&[u8]]) -> Vec<u8> {diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/generated.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/generated.rsindex 0c4b3685608..ed5f8b2d884 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/generated.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/generated.rs@@ -16,9 +16,10 @@ use super::recorder::{Proxy, bytes_of, bytes_of_mut, copy_reply_data, gen_count, leading_bytes, leading_bytes_mut, payload_size,until_nul,};+use libcompositing_rust::webgl::vocabulary::{commands, sync_calls};+use libcompositing_rust::webgl::wire::{DataSpan, InlineData, WireStruct};+use super::transport::Transport;-use super::vocabulary::{commands, sync_calls};-use super::wire::{DataSpan, InlineData, WireStruct};use crate::web_gl::constants::GL_COLOR;include!(concat!(env!("OUT_DIR"), "/webgl_proxy.rs"));diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/mod.rsindex a8053cbf57f..814ac846a0a 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/mod.rs@@ -5,14 +5,12 @@*///! The recording side of the WebGL command stream. Libraries/LibCompositing/WebGL is the replaying side, and-//! GLFunctions.json there defines what crosses the stream for both.+//! GLFunctions.json there defines what crosses the stream for both, as libcompositing_rust::webgl.pub(crate) mod custom;pub(crate) mod generated;pub(crate) mod recorder;pub(crate) mod transport;-pub(crate) mod vocabulary;-pub(crate) mod wire;#[cfg(test)]mod tests;diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/recorder.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/recorder.rsindex 08b2dc21f0e..b9a0d91ca44 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/recorder.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/recorder.rs@@ -13,18 +13,15 @@ use core::ptr;use core::sync::atomic::{AtomicU64, Ordering};use std::rc::Rc;-use super::transport::{SharedMemory, Transport};-use super::vocabulary::{CommandType, MAX_COMMAND_STRUCT_SIZE};-use super::wire::{+use libcompositing_rust::webgl::vocabulary::{CommandType, MAX_COMMAND_STRUCT_SIZE};+use libcompositing_rust::webgl::wire::{Command, DataSpan, HEADER_SIZE, InlineData, Record, SyncReply, SyncRequest, encode_sync_request,padded_record_size, resolve_data_span,};-use crate::web_gl::constants::GL_OUT_OF_MEMORY;+use libcompositing_rust::webgl::{DEFAULT_SHARED_DATA_REGION_CAPACITY, SHARED_DATA_REGION_OFFSET};-/// 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(crate) const SHARED_DATA_REGION_OFFSET: usize = 128;-pub(crate) const DEFAULT_SHARED_DATA_REGION_CAPACITY: usize = 32 * 1024 * 1024;+use super::transport::{SharedMemory, Transport};+use crate::web_gl::constants::GL_OUT_OF_MEMORY;pub(crate) const MAX_PENDING_COMMAND_BYTES: usize = 4 * 1024 * 1024;diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/tests.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/tests.rsindex f01dc471b72..7937d8773a1 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/tests.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/tests.rs@@ -14,10 +14,12 @@ use std::rc::{Rc, Weak};use super::custom::FrameUpload;use super::generated::GetActiveAttribOutputs;-use super::recorder::{MAX_PENDING_COMMAND_BYTES, Proxy, SHARED_DATA_REGION_OFFSET, bytes_of};+use libcompositing_rust::webgl::SHARED_DATA_REGION_OFFSET;+use libcompositing_rust::webgl::vocabulary::{CommandType, SyncCallType, commands, sync_calls};+use libcompositing_rust::webgl::wire::{Command, DataSpan, HEADER_SIZE, WireStruct};++use super::recorder::{MAX_PENDING_COMMAND_BYTES, Proxy, bytes_of};use super::transport::{ReadPixelsResult, SharedMemory, Transport};-use super::vocabulary::{CommandType, SyncCallType, commands, sync_calls};-use super::wire::{DataSpan, HEADER_SIZE, WireStruct};use crate::web_gl::constants::{GL_ARRAY_BUFFER, GL_INVALID_ENUM, GL_OUT_OF_MEMORY, GL_RGBA, GL_UNSIGNED_BYTE};#[derive(Clone)]@@ -77,7 +79,7 @@ fn records_in(mut bytes: &[u8]) -> Vec<Record> {records}-fn record_of<C: super::wire::Command>(command: &C) -> Record {+fn record_of<C: Command>(command: &C) -> Record {let mut payload = command.as_bytes().to_vec();payload.resize((HEADER_SIZE + payload.len()).next_multiple_of(16) - HEADER_SIZE, 0);Record {diff --git a/Libraries/LibWeb/WebGL/RemoteWebGLTransportFFI.cpp b/Libraries/LibWeb/WebGL/RemoteWebGLTransportFFI.cppindex ace91e10809..21d32f9853b 100644--- a/Libraries/LibWeb/WebGL/RemoteWebGLTransportFFI.cpp+++ b/Libraries/LibWeb/WebGL/RemoteWebGLTransportFFI.cpp@@ -51,7 +51,7 @@ static_assert(offsetof(Compositing::WebGL::WebGLSyncCallHeader, type) == 0 && ofstatic_assert(sizeof(Compositing::WebGL::WebGLSyncCallType) == sizeof(u16) && sizeof(Compositing::WebGL::WebGLCommandType) == sizeof(u16));static_assert(sizeof(Compositing::WebGL::WebGLCommandHeader::payload_size) == sizeof(u32));-// NB: `DataSpan` of proxy/wire.rs is two `u32`s in this order.+// NB: `DataSpan` of libcompositing_rust::webgl::wire is two `u32`s in this order.static_assert(sizeof(Compositing::WebGL::WebGLDataSpan) == 2 * sizeof(u32));static_assert(offsetof(Compositing::WebGL::WebGLDataSpan, offset) == 0);static_assert(offsetof(Compositing::WebGL::WebGLDataSpan, size) == sizeof(u32));