Truly independent web browser
LibWeb+LibIPC+Compositor: Rasterize display lists with a sync request
Aliaksandr Kalenik32fb0ea5ba7d
diff --git a/Libraries/LibIPC/Connection.h b/Libraries/LibIPC/Connection.hindex 371ec222d30..221572ca1be 100644--- a/Libraries/LibIPC/Connection.h+++ b/Libraries/LibIPC/Connection.h@@ -18,6 +18,7 @@#include <AK/Time.h>#include <LibCore/EventReceiver.h>#include <LibIPC/Attachment.h>+#include <LibIPC/FfiConnection.h>#include <LibIPC/Forward.h>#include <LibIPC/Message.h>#include <LibIPC/RawMessage.h>@@ -53,14 +54,6 @@ private:Transport* m_transport_waited_on { nullptr };};-struct FfiConnection {- void* connection_with_one_reference;- bool (*send_sync_request)(void* connection, ReadonlyBytes, ReadonlySpan<RawAttachment>, u32 response_endpoint_magic, i32 response_message_id, void* response_sink, void (*take_response)(void* response_sink, FfiRawMessage));- void (*ref)(void* connection);- void (*unref)(void* connection);-};-static_assert(sizeof(FfiConnection) == 4 * sizeof(void*), "FfiConnection of libipc_rust is written to match this by hand");-class ConnectionBase : public Core::EventReceiver {C_OBJECT_ABSTRACT(ConnectionBase);diff --git a/Libraries/LibIPC/FfiConnection.h b/Libraries/LibIPC/FfiConnection.hnew file mode 100644index 00000000000..901e657ce85--- /dev/null+++ b/Libraries/LibIPC/FfiConnection.h@@ -0,0 +1,23 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Span.h>+#include <LibIPC/RawAttachment.h>+#include <LibIPC/RawMessage.h>++namespace IPC {++struct FfiConnection {+ void* connection_with_one_reference;+ bool (*send_sync_request)(void* connection, ReadonlyBytes, ReadonlySpan<RawAttachment>, u32 response_endpoint_magic, i32 response_message_id, void* response_sink, void (*take_response)(void* response_sink, FfiRawMessage));+ void (*ref)(void* connection);+ void (*unref)(void* connection);+};+static_assert(sizeof(FfiConnection) == 4 * sizeof(void*), "FfiConnection of libipc_rust is written to match this by hand");++}diff --git a/Libraries/LibWeb/Compositor/CompositorConnection.cpp b/Libraries/LibWeb/Compositor/CompositorConnection.cppindex 5903dd2f6ab..b8c50ec492f 100644--- a/Libraries/LibWeb/Compositor/CompositorConnection.cpp+++ b/Libraries/LibWeb/Compositor/CompositorConnection.cpp@@ -481,9 +481,7 @@ bool CompositorConnection::rasterize_image(Layout::RustFFI::FfiImageRasterizatio// The compositor draws straight into the target, so it has to be memory both processes can map.VERIFY(target->anonymous_buffer().is_valid());auto token = m_next_rasterization_token++;- if (!Layout::RustFFI::render_state_rasterize_image(m_poster->to_ffi_with_one_reference(), token, &image, target.ptr()))- return false;- return wait_for_rasterization(token);+ return did_rasterize(Layout::RustFFI::render_state_rasterize_image(to_ffi_with_one_reference(), m_poster->to_ffi_with_one_reference(), token, &image, target.ptr()));}bool CompositorConnection::rasterize_last_recording(Layout::RustFFI::DocumentHost const& document_host, Layout::BegunRead const& read, NonnullRefPtr<Gfx::Bitmap> target)@@ -494,27 +492,21 @@ bool CompositorConnection::rasterize_last_recording(Layout::RustFFI::DocumentHos// The compositor draws straight into the target, so it has to be memory both processes can map.VERIFY(target->anonymous_buffer().is_valid());auto token = m_next_rasterization_token++;- if (!Layout::RustFFI::render_state_rasterize_last_recording(m_poster->to_ffi_with_one_reference(), token, &document_host, &read, target.ptr()))- return false;- return wait_for_rasterization(token);+ return did_rasterize(Layout::RustFFI::render_state_rasterize_last_recording(to_ffi_with_one_reference(), m_poster->to_ffi_with_one_reference(), token, &document_host, &read, target.ptr()));}-bool CompositorConnection::wait_for_rasterization(u64 token)+bool CompositorConnection::did_rasterize(Layout::RustFFI::RasterizationOutcome outcome){- while (true) {- auto answer = wait_for_specific_endpoint_message<Messages::CompositorWebContentClient::DidRasterizeDisplayList>();- if (!answer) {- did_lose_compositor();- return false;- }- if (answer->token() == token)- return answer->success();+ switch (outcome) {+ case Layout::RustFFI::RasterizationOutcome::Rasterized:+ return true;+ case Layout::RustFFI::RasterizationOutcome::NotRasterized:+ return false;+ case Layout::RustFFI::RasterizationOutcome::CompositorLost:+ did_lose_compositor();+ return false;}-}--void CompositorConnection::did_rasterize_display_list(u64, bool)-{- // CompositorConnection::wait_for_rasterization() waits for its answer, and an answer it gave up on goes nowhere.+ VERIFY_NOT_REACHED();}void CompositorConnection::invalidate_keyboard_scroll_state(Web::CompositorContextId context_id, u64 generation)diff --git a/Libraries/LibWeb/Compositor/CompositorConnection.h b/Libraries/LibWeb/Compositor/CompositorConnection.hindex 599629e265c..c975911041d 100644--- a/Libraries/LibWeb/Compositor/CompositorConnection.h+++ b/Libraries/LibWeb/Compositor/CompositorConnection.h@@ -32,6 +32,7 @@ namespace Web::Layout::RustFFI {struct DocumentHost;struct FfiImageRasterization;+enum class RasterizationOutcome : u8;}@@ -133,8 +134,7 @@ private:virtual void rendering_opportunity(Web::CompositorContextId, i64 frame_time_nanoseconds, double frame_interval_milliseconds) override;virtual void async_scroll_updates(Web::CompositorContextId, Compositing::PendingAsyncScrollUpdates) override;virtual void animated_content_moved_under_pointer(Web::CompositorContextId, i64 frame_time_nanoseconds) override;- virtual void did_rasterize_display_list(u64 token, bool success) override;- bool wait_for_rasterization(u64 token);+ bool did_rasterize(Layout::RustFFI::RasterizationOutcome);virtual void did_complete_screenshot(Compositing::ScreenshotRequestId) override;virtual void did_fail_screenshot(Compositing::ScreenshotRequestId) override;virtual void paint_contexts_for_screenshot(u64 preparation_id, Vector<Web::CompositorContextId>) override;diff --git a/Libraries/LibWeb/Rust/build.rs b/Libraries/LibWeb/Rust/build.rsindex f558bb01d84..023bde2ae71 100644--- a/Libraries/LibWeb/Rust/build.rs+++ b/Libraries/LibWeb/Rust/build.rs@@ -3357,6 +3357,13 @@ fn main() -> Result<(), Box<dyn Error>> {layout_config.includes.push("LibIPC/ThreadSafeMessagePoster.h".to_string());+ // Rust sends synchronous requests to the compositor through the connection C++ made.+ layout_config.export.exclude.push("FfiConnection".to_string());+ layout_config+ .export+ .rename+ .insert("FfiConnection".to_string(), "IPC::FfiConnection".to_string());+ layout_config.includes.push("LibIPC/FfiConnection.h".to_string());// A compositor animation carries its effect's timing as the animations header describes it.layout_config.export.exclude.push("AnimationEffectTiming".to_string());layout_config.export.rename.insert(diff --git a/Libraries/LibWeb/Rust/src/painting/rasterize.rs b/Libraries/LibWeb/Rust/src/painting/rasterize.rsindex ea02492baa4..2b22d216e45 100644--- a/Libraries/LibWeb/Rust/src/painting/rasterize.rs+++ b/Libraries/LibWeb/Rust/src/painting/rasterize.rs@@ -23,7 +23,7 @@ use libcompositing_rust::ipc_types::compositor_web_content_server::messages::Rasuse libgfx_rust::font::FontHandle;use libgfx_rust::image_frame::ImageFrameHandle;use libgfx_rust::{CompositingAndBlendingOperator, FloatRect, IntSize, ScalingMode};-use libipc_rust::cpp_connection::FfiThreadSafeMessagePoster;+use libipc_rust::cpp_connection::{CppConnection, FfiConnection, FfiThreadSafeMessagePoster};use std::ffi::c_void;use std::sync::Arc;@@ -127,10 +127,18 @@ unsafe fn record_image(image: &FfiImageRasterization) -> (RecordedDisplayList, D(recorder.into_builder().finish(), resources)}-/// Stages what the display list draws under `token` and hands it to the compositor to rasterize into `target_bitmap`,-/// against `tree`, the visual context tree it was recorded against. Answers whether the compositor could still be-/// reached.-fn post_rasterization(+#[repr(u8)]+pub enum RasterizationOutcome {+ Rasterized,+ NotRasterized,+ CompositorLost,+}++/// Stages what the display list draws under `token` and has the compositor rasterize it into `target_bitmap`, against+/// `tree`, the visual context tree it was recorded against.+#[allow(clippy::too_many_arguments)]+fn rasterize(+ connection: &CppConnection,poster: &CompositorPoster,token: u64,display_list: &RecordedDisplayList,@@ -138,14 +146,14 @@ fn post_rasterization(root_group_color: libgfx_rust::Color,resources: &DisplayListResources,target_bitmap: *const c_void,-) -> bool {+) -> RasterizationOutcome {let display_list = display_list_holding_vector_image_records(display_list, &resources.vector_images);let resources = resources.with_vector_image_resources();let fonts: Vec<FontHandle> = resources.fonts.values().cloned().collect();let image_frames: Vec<ImageFrameHandle> = resources.image_frames.values().cloned().collect();// SAFETY: The caller keeps the bitmap live for the call.if !unsafe { poster.stage_rasterization(token, &fonts, &image_frames, target_bitmap) } {- return false;+ return RasterizationOutcome::NotRasterized;}// The list goes whole, as chunks named by what the compositor replays.let chunks: Vec<Chunk> = chunks_of(&display_list.bytes, &display_list.command_runs, &display_list.chunks)@@ -175,34 +183,41 @@ fn post_rasterization("WebContent: Could not place a {} byte display list to rasterize in shared memory",display_list.bytes.len());- return false;+ return RasterizationOutcome::NotRasterized;};- poster.post(RasterizeDisplayList {+ match connection.send_sync(RasterizeDisplayList {token,display_list,visual_context_tree: tree,- })+ }) {+ Some(response) if response.success => RasterizationOutcome::Rasterized,+ Some(_) => RasterizationOutcome::NotRasterized,+ None => RasterizationOutcome::CompositorLost,+ }}-/// Has the compositor rasterize `image` into `target_bitmap`, a shareable `Gfx::Bitmap`, through `poster`, under `token`,-/// which the compositor's answer names. Answers whether the image went to the compositor.+/// Has the compositor rasterize `image` into `target_bitmap`, a shareable `Gfx::Bitmap`, under `token`, and waits for it+/// to.////// # Safety///-/// `poster` must hold one reference to a live poster on the transport of the connection to the compositor, which the-/// caller gives up, and what `image` points at and `target_bitmap` must be live for the call.+/// `connection` must hold one reference to the live connection to the compositor of this thread, and `poster` one+/// reference to a live poster on its transport, which the caller gives up, and what `image` points at and+/// `target_bitmap` must be live for the call.#[unsafe(no_mangle)]pub unsafe extern "C" fn render_state_rasterize_image(+ connection: FfiConnection,poster: FfiThreadSafeMessagePoster,token: u64,image: &FfiImageRasterization,target_bitmap: *const c_void,-) -> bool {+) -> RasterizationOutcome {// SAFETY: Guaranteed by the caller.- let poster = unsafe { CompositorPoster::adopt(poster) };+ let (connection, poster) = unsafe { (CppConnection::adopt(connection), CompositorPoster::adopt(poster)) };// SAFETY: As above.let (display_list, resources) = unsafe { record_image(image) };- post_rasterization(+ rasterize(+ &connection,&poster,token,&display_list,@@ -214,33 +229,34 @@ pub unsafe extern "C" fn render_state_rasterize_image(}/// Has the compositor rasterize the recording the document of `host` took in last into `target_bitmap`, a shareable-/// `Gfx::Bitmap` the size of the document's viewport, through `poster`, under `token`, which the compositor's answer-/// names. Answers whether the recording went to the compositor.+/// `Gfx::Bitmap` the size of the document's viewport, under `token`, and waits for it to.////// # Safety///-/// `poster` must hold one reference to a live poster on the transport of the connection to the compositor, which the-/// caller gives up, `host` must be a live document host, on its document's thread, and `target_bitmap` must be live for-/// the call.+/// `connection` must hold one reference to the live connection to the compositor of this thread, and `poster` one+/// reference to a live poster on its transport, which the caller gives up, `host` must be a live document host, on its+/// document's thread, and `target_bitmap` must be live for the call.#[unsafe(no_mangle)]pub unsafe extern "C" fn render_state_rasterize_last_recording(+ connection: FfiConnection,poster: FfiThreadSafeMessagePoster,token: u64,host: &DocumentHost,read: &crate::render_state::BegunRead,target_bitmap: *const c_void,-) -> bool {+) -> RasterizationOutcome {// SAFETY: Guaranteed by the caller.- let poster = unsafe { CompositorPoster::adopt(poster) };+ let (connection, poster) = unsafe { (CppConnection::adopt(connection), CompositorPoster::adopt(poster)) };let recording =crate::painting::ffi::read_arena(host, read, (), |arena, ()| arena.paint_state().last_recording.clone());let Some((recording, tree)) = recording.and_then(|recording| {let tree = recording.visual_context_tree.clone()?;Some((recording, tree))}) else {- return false;+ return RasterizationOutcome::NotRasterized;};- post_rasterization(+ rasterize(+ &connection,&poster,token,&recording.display_list,diff --git a/Services/Compositor/CompositorWebContentClient.ipc b/Services/Compositor/CompositorWebContentClient.ipcindex 17ec14b7a94..fa4759bbe72 100644--- a/Services/Compositor/CompositorWebContentClient.ipc+++ b/Services/Compositor/CompositorWebContentClient.ipc@@ -15,8 +15,6 @@ endpoint CompositorWebContentClient// as of the frame's time.[RustSender] animated_content_moved_under_pointer(Web::CompositorContextId context_id, i64 frame_time_nanoseconds) =|[RustSender] overlay_scrollbar_visibilities_changed(Vector<Web::OverlayScrollbarVisibility> visibilities) =|- // The compositor rasterized the display list that the rasterize_display_list() naming `token` handed it, or failed to.- [RustSender] did_rasterize_display_list(u64 token, bool success) =|did_complete_screenshot(Compositing::ScreenshotRequestId request_id) =|did_fail_screenshot(Compositing::ScreenshotRequestId request_id) =|paint_contexts_for_screenshot(u64 preparation_id, Vector<Web::CompositorContextId> context_ids) =|diff --git a/Services/Compositor/CompositorWebContentServer.ipc b/Services/Compositor/CompositorWebContentServer.ipcindex 5e4f386d5d1..44e33afa5ac 100644--- a/Services/Compositor/CompositorWebContentServer.ipc+++ b/Services/Compositor/CompositorWebContentServer.ipc@@ -74,10 +74,9 @@ endpoint CompositorWebContentServerget_placeholder_canvas_pixels(Compositing::CanvasId canvas_id, Gfx::IntRect rect) => (Gfx::ShareableBitmap pixels, bool origin_clean)// A display list is rasterized into the target bitmap with the fonts and the registered image frames staged for- // it under a token that the next rasterize_display_list names. The compositor answers with- // did_rasterize_display_list().+ // it under a token that the next rasterize_display_list names.stage_rasterization(u64 token, Vector<Compositing::DisplayListFontDescription> fonts, Vector<Compositing::ImageFrameResourceId> image_frame_ids, Gfx::ShareableBitmap target_bitmap) =|- [RustReceiver, RustSender] rasterize_display_list(u64 token, Compositing::DisplayList display_list, Compositing::VisualContextTree visual_context_tree) =|+ [RustReceiver, RustSender] rasterize_display_list(u64 token, Compositing::DisplayList display_list, Compositing::VisualContextTree visual_context_tree) => (bool success)// Only Rust sends and receives the messages of WebGL contexts. The commands of a context name the images that they// upload by their position among the image sources sent with them.diff --git a/Services/Compositor/Rust/src/core/messages.rs b/Services/Compositor/Rust/src/core/messages.rsindex af4ca77fdd0..fc4ae771525 100644--- a/Services/Compositor/Rust/src/core/messages.rs+++ b/Services/Compositor/Rust/src/core/messages.rs@@ -26,21 +26,21 @@ use libcompositing_rust::ipc_types::compositor_presentation_client::messages::Diuse libcompositing_rust::ipc_types::compositor_presentation_server::messages::{HandleAndDispatchKeyEvent, HandleAndDispatchMouseEvent, HandleAndDispatchPinchEvent,};-use libcompositing_rust::ipc_types::compositor_web_content_client::messages::DidRasterizeDisplayList;use libcompositing_rust::ipc_types::compositor_web_content_server::messages::{ApplyScrollRequests, BeginInputTraceForTesting, BeginInputTraceForTestingResponse,ClearPerTestInputStateForTesting, ClearPerTestInputStateForTestingResponse, CreateCanvas2dContext,CreateWebglContext, CreateWebglContextResponse, DestroyCanvas2dContext, DestroyWebglContext,InvalidateKeyboardScrollState, InvalidateKeyboardScrollStateResponse, InvalidateWheelEventListenerState,- RasterizeDisplayList, ReserveCanvasIds, ReserveCanvasIdsResponse, RouteFirstWheelStepForTesting,- RouteFirstWheelStepForTestingResponse, ScrollStateForTesting, ScrollStateForTestingResponse,- TakeInputTraceForTesting, TakeInputTraceForTestingResponse, TakePendingAsyncScrollUpdates,- TakePendingAsyncScrollUpdatesResponse, TakeWheelEventFromMainThread, TakeWheelEventFromMainThreadResponse,- UpdateCanvas2dStream, UpdateDisplayList, UpdateScrollState, UpdateVisualContextTree, WebglClearDrawingBuffer,- WebglCommands, WebglCommandsFromSharedBuffer, WebglDrainCommandBuffer, WebglDrainCommandBufferResponse,- WebglPresentCanvas, WebglReadBackDrawingBuffer, WebglReadBackDrawingBufferResponse, WebglReadBufferSubData,- WebglReadBufferSubDataResponse, WebglReadPixels, WebglReadPixelsResponse, WebglSetCommandBuffer, WebglSyncCall,- WebglSyncCallResponse, WheelEventCanceled, WheelEventLetThrough, WheelEventLetThroughResponse,+ RasterizeDisplayList, RasterizeDisplayListResponse, ReserveCanvasIds, ReserveCanvasIdsResponse,+ RouteFirstWheelStepForTesting, RouteFirstWheelStepForTestingResponse, ScrollStateForTesting,+ ScrollStateForTestingResponse, TakeInputTraceForTesting, TakeInputTraceForTestingResponse,+ TakePendingAsyncScrollUpdates, TakePendingAsyncScrollUpdatesResponse, TakeWheelEventFromMainThread,+ TakeWheelEventFromMainThreadResponse, UpdateCanvas2dStream, UpdateDisplayList, UpdateScrollState,+ UpdateVisualContextTree, WebglClearDrawingBuffer, WebglCommands, WebglCommandsFromSharedBuffer,+ WebglDrainCommandBuffer, WebglDrainCommandBufferResponse, WebglPresentCanvas, WebglReadBackDrawingBuffer,+ WebglReadBackDrawingBufferResponse, WebglReadBufferSubData, WebglReadBufferSubDataResponse, WebglReadPixels,+ WebglReadPixelsResponse, WebglSetCommandBuffer, WebglSyncCall, WebglSyncCallResponse, WheelEventCanceled,+ WheelEventLetThrough, WheelEventLetThroughResponse,};use libcompositing_rust::ipc_types::{Compositing_RemoteLayerHostHandle, Compositing_RemoteLayerHostKind, Compositing_WebGL_WebGLVersion,@@ -712,13 +712,13 @@ impl compositor_web_content_server::Stub for MessagesFromWebContent<'_> {Ok(())}- fn rasterize_display_list(&mut self, message: RasterizeDisplayList) -> Result<(), Misbehavior> {- let token = message.token;- let success = self.rasterize_staged_display_list(message)?;- self.core- .host- .post_to_web_content(self.client_id, DidRasterizeDisplayList { token, success });- Ok(())+ fn rasterize_display_list(+ &mut self,+ message: RasterizeDisplayList,+ ) -> Result<RasterizeDisplayListResponse, Misbehavior> {+ Ok(RasterizeDisplayListResponse {+ success: self.rasterize_staged_display_list(message)?,+ })}fn update_scroll_state(&mut self, message: UpdateScrollState) -> Result<(), Misbehavior> {