Truly independent web browser
LibWeb+LibCompositing: Decode render clock messages in Rust
Aliaksandr Kalenikdab0ef19e389
diff --git a/Cargo.lock b/Cargo.lockindex 56594e31464..1b09a63db07 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1749,6 +1749,7 @@ dependencies = ["foldhash 0.2.0","ladybird_allocator","libgfx_rust",+ "libipc_rust","rustc-demangle",]@@ -2019,6 +2020,7 @@ dependencies = ["ladybird_allocator","libcompositing_rust","libgfx_rust",+ "libipc_rust","liburl_rust","libweb_html_tokenizer","rayon",diff --git a/Libraries/LibCompositing/Rust/Cargo.toml b/Libraries/LibCompositing/Rust/Cargo.tomlindex 3cf54006189..931ae3dfaad 100644--- a/Libraries/LibCompositing/Rust/Cargo.toml+++ b/Libraries/LibCompositing/Rust/Cargo.toml@@ -15,6 +15,7 @@ ak = { path = "../../../AK/Rust" }foldhash = "0.2"ladybird_allocator = { path = "../../RustAllocator", optional = true }libgfx_rust = { path = "../../LibGfx/Rust", default-features = false }+libipc_rust = { path = "../../LibIPC/Rust" }rustc-demangle = "0.1"[build-dependencies]diff --git a/Libraries/LibCompositing/Rust/build.rs b/Libraries/LibCompositing/Rust/build.rsindex ef2a47dfbe7..a9158062f20 100644--- a/Libraries/LibCompositing/Rust/build.rs+++ b/Libraries/LibCompositing/Rust/build.rs@@ -7,6 +7,7 @@use std::env;use std::error::Error;use std::path::{Path, PathBuf};+use std::process::Command;// 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@@ -259,10 +260,43 @@ fn display_list_payload_alignment(path: &Path) -> Result<String, Box<dyn Error>>Ok(value.to_string())}+fn generate_ipc_endpoints(manifest_dir: &Path, out_dir: &Path) -> Result<(), Box<dyn Error>> {+ let source_dir = manifest_dir.join("../../..");+ let generator = source_dir.join("Meta/Generators/generate_ipc_definitions.py");+ println!("cargo:rerun-if-changed={}", generator.display());+ for module in ["lexer.py", "utils.py"] {+ println!(+ "cargo:rerun-if-changed={}",+ source_dir.join("Meta/Utils").join(module).display()+ );+ }++ println!("cargo:rerun-if-env-changed=PYTHON");+ let python = env::var_os("PYTHON").unwrap_or_else(|| if cfg!(windows) { "python" } else { "python3" }.into());+ for endpoint in ["RenderClockClient", "RenderClockServer"] {+ let definition = source_dir.join(format!("Services/Compositor/{endpoint}.ipc"));+ println!("cargo:rerun-if-changed={}", definition.display());+ let output = out_dir.join(format!("{endpoint}Endpoint.rs"));+ let status = Command::new(&python)+ .arg(&generator)+ .arg("--input")+ .arg(&definition)+ .arg("--rust-output")+ .arg(&output)+ .status()?;+ if !status.success() {+ return Err(format!("IPC endpoint generation failed for {endpoint}").into());+ }+ }+ 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_endpoints(&manifest_dir, &out_dir)?;+println!("cargo:rerun-if-changed=build.rs");println!("cargo:rerun-if-changed=cbindgen.toml");println!("cargo:rerun-if-changed=src");diff --git a/Libraries/LibCompositing/Rust/src/ipc_types.rs b/Libraries/LibCompositing/Rust/src/ipc_types.rsnew file mode 100644index 00000000000..1126e3a4f13--- /dev/null+++ b/Libraries/LibCompositing/Rust/src/ipc_types.rs@@ -0,0 +1,172 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The types the Compositor's endpoints carry, under the names the IPC compiler gives them, and the endpoints it+//! generates from Services/Compositor/*.ipc for the messages that name Rust.++#![allow(non_camel_case_types)]++use crate::css_pixels::{CssPixelPoint, CssPixels};+use crate::display_list::commands::{CompositorContextId, UniqueNodeId};+use libipc_rust::wire::{Decode, DecodeError, Decoder, Encode, EncodeError, Encoder};++pub type Web_CompositorContextId = CompositorContextId;+pub type Web_UniqueNodeID = UniqueNodeId;+pub type Web_CSSPixelPoint = CssPixelPoint;++impl Encode for CompositorContextId {+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {+ encoder.encode(&self.0)+ }+}++impl Decode for CompositorContextId {+ const MIN_ENCODED_SIZE: usize = size_of::<u64>();++ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ Ok(Self(decoder.decode()?))+ }+}++impl Encode for UniqueNodeId {+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {+ encoder.encode(&self.0)+ }+}++impl Decode for UniqueNodeId {+ const MIN_ENCODED_SIZE: usize = size_of::<i64>();++ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ Ok(Self(decoder.decode()?))+ }+}++impl Encode for CssPixelPoint {+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {+ encoder.encode(&self.x.raw_value())?;+ encoder.encode(&self.y.raw_value())+ }+}++impl Decode for CssPixelPoint {+ const MIN_ENCODED_SIZE: usize = 2 * size_of::<i32>();++ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ Ok(Self {+ x: CssPixels::from_raw(decoder.decode()?),+ y: CssPixels::from_raw(decoder.decode()?),+ })+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+#[repr(u8)]+pub enum Web_AsyncScrollNodeKind {+ Viewport,+ Element,+ PseudoElement,+ VisualViewport,+}++impl Encode for Web_AsyncScrollNodeKind {+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {+ encoder.encode(&(*self as u8))+ }+}++impl Decode for Web_AsyncScrollNodeKind {+ const MIN_ENCODED_SIZE: usize = size_of::<u8>();++ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ match decoder.decode::<u8>()? {+ 0 => Ok(Self::Viewport),+ 1 => Ok(Self::Element),+ 2 => Ok(Self::PseudoElement),+ 3 => Ok(Self::VisualViewport),+ _ => Err(DecodeError::InvalidValue("Web::AsyncScrollNodeKind")),+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub struct Web_AsyncScrollNodeStableID {+ pub node_id: UniqueNodeId,+ pub kind: Web_AsyncScrollNodeKind,+ pub pseudo_element_type: u8,+}++impl Encode for Web_AsyncScrollNodeStableID {+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {+ encoder.encode(&self.node_id)?;+ encoder.encode(&self.kind)?;+ encoder.encode(&self.pseudo_element_type)+ }+}++impl Decode for Web_AsyncScrollNodeStableID {+ const MIN_ENCODED_SIZE: usize =+ UniqueNodeId::MIN_ENCODED_SIZE + Web_AsyncScrollNodeKind::MIN_ENCODED_SIZE + size_of::<u8>();++ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ Ok(Self {+ node_id: decoder.decode()?,+ kind: decoder.decode()?,+ pseudo_element_type: decoder.decode()?,+ })+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Web_CompositorScrollOffset {+ pub scroll_node: Web_AsyncScrollNodeStableID,+ pub offset: CssPixelPoint,+}++impl Encode for Web_CompositorScrollOffset {+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {+ encoder.encode(&self.scroll_node)?;+ encoder.encode(&self.offset)+ }+}++impl Decode for Web_CompositorScrollOffset {+ const MIN_ENCODED_SIZE: usize = Web_AsyncScrollNodeStableID::MIN_ENCODED_SIZE + CssPixelPoint::MIN_ENCODED_SIZE;++ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ Ok(Self {+ scroll_node: decoder.decode()?,+ offset: decoder.decode()?,+ })+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Web_DevicePixelPoint {+ pub x: i32,+ pub y: i32,+}++impl Encode for Web_DevicePixelPoint {+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {+ encoder.encode(&self.x)?;+ encoder.encode(&self.y)+ }+}++impl Decode for Web_DevicePixelPoint {+ const MIN_ENCODED_SIZE: usize = 2 * size_of::<i32>();++ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {+ Ok(Self {+ x: decoder.decode()?,+ y: decoder.decode()?,+ })+ }+}++include!(concat!(env!("OUT_DIR"), "/RenderClockClientEndpoint.rs"));+include!(concat!(env!("OUT_DIR"), "/RenderClockServerEndpoint.rs"));diff --git a/Libraries/LibCompositing/Rust/src/lib.rs b/Libraries/LibCompositing/Rust/src/lib.rsindex bad580ad4b2..52bf9c2047b 100644--- a/Libraries/LibCompositing/Rust/src/lib.rs+++ b/Libraries/LibCompositing/Rust/src/lib.rs@@ -21,6 +21,7 @@ pub mod ffi;pub mod filter_bytes;pub mod force_dark;pub mod host;+pub mod ipc_types;pub mod node_slot_id;#[cfg(test)]mod test_stubs;diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex 7d2181c60c1..64ea9a69b97 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -1096,6 +1096,7 @@ sync_rust_crate_ffi_headers(SelectorStateFactsGenerated.incLayout/TreeBuilderRustFFI.hLayout/LayoutRustFFI.h+ Compositor/RenderClockRustFFI.h)add_dependencies(LibWeb libweb_rust-ffi-headers)target_link_libraries(libweb_bindings_rust INTERFACE LibGfx LibGC LibUnicode)diff --git a/Libraries/LibWeb/Compositor/RenderClock.cpp b/Libraries/LibWeb/Compositor/RenderClock.cppindex 3fa04400d3d..c565d092edd 100644--- a/Libraries/LibWeb/Compositor/RenderClock.cpp+++ b/Libraries/LibWeb/Compositor/RenderClock.cpp@@ -14,7 +14,7 @@#include <LibIPC/Transport.h>#include <LibThreading/Thread.h>#include <LibWeb/Compositor/RenderClock.h>-#include <LibWeb/Layout/LayoutRustFFI.h>+#include <LibWeb/Compositor/RenderClockRustFFI.h>namespace Web::Compositor {@@ -38,28 +38,18 @@ private:m_clock.did_lose_channel();}- virtual void clock_tick(Web::CompositorContextId context_id, i64 frame_time_nanoseconds, double, Vector<Web::CompositorScrollOffset> scroll_offsets) override+ virtual ErrorOr<OwnPtr<IPC::MessageBuffer>> handle_raw(IPC::RawMessage& message) override{- if (!m_detached)- m_clock.did_receive_clock_tick(context_id, frame_time_nanoseconds, scroll_offsets);- }-- virtual void pointer_moved(Web::CompositorContextId context_id, Web::DevicePixelPoint position, u32 buttons, bool scrolled_since_frame, u64 input_event_id) override- {- if (!m_detached)- m_clock.did_receive_pointer_move(context_id, Gfx::FloatPoint { position.x().value(), position.y().value() }, buttons, scrolled_since_frame, input_event_id);- }-- virtual void pointer_left(Web::CompositorContextId context_id, u64 input_event_id) override- {- if (!m_detached)- m_clock.did_receive_pointer_move(context_id, {}, 0, false, input_event_id);- }-- virtual void pointer_rests_on_moving_content(Web::CompositorContextId context_id) override- {- if (!m_detached)- m_clock.did_receive_pointer_rest(context_id);+ if (m_detached)+ return nullptr;+ auto outcome = message.hand_to_rust([&](IPC::FfiRawMessage raw_message) {+ RustFFI::render_clock_lanes_handle_message(&m_clock.m_lanes, raw_message, m_clock.is_manual_for_testing());+ });+ if (outcome.misbehavior.has_value()) {+ dbgln("RenderClock: Disconnecting the Compositor after {}: {}", message.message_name(), *outcome.misbehavior);+ shutdown();+ }+ return nullptr;}RenderClock& m_clock;@@ -72,29 +62,6 @@ ClockTicksHandle::~ClockTicksHandle()Layout::RustFFI::clock_ticks_release(m_ticks);}-bool ClockTicksHandle::tick(i64 frame_time_nanoseconds, ReadonlySpan<Web::CompositorScrollOffset> scroll_offsets) const-{- // A scroll timeline follows the scroll node of an element or a document's viewport, which its unique id names.- Vector<Layout::RustFFI::FfiScrollOffset, 8> scrollers;- for (auto const& scroll_offset : scroll_offsets) {- if (scroll_offset.scroll_node.kind == Web::AsyncScrollNodeKind::PseudoElement)- continue;- scrollers.append({ scroll_offset.scroll_node.node_id.value(), scroll_offset.offset.x().to_double(), scroll_offset.offset.y().to_double() });- }- return Layout::RustFFI::clock_ticks_tick(m_ticks, frame_time_nanoseconds, scrollers.span());-}--PointerAnswer ClockTicksHandle::pointer_moved(Optional<Gfx::FloatPoint> device_position, u32 buttons, bool scrolled_since_frame, u64 input_event_id) const-{- auto position = device_position.value_or({});- return static_cast<PointerAnswer>(Layout::RustFFI::clock_ticks_pointer_moved(m_ticks, device_position.has_value(), position.x(), position.y(), buttons, scrolled_since_frame, input_event_id));-}--PointerAnswer ClockTicksHandle::pointer_rests_on_moving_content() const-{- return static_cast<PointerAnswer>(Layout::RustFFI::clock_ticks_pointer_rests_on_moving_content(m_ticks));-}-RenderClock& RenderClock::the(){// The clock lives as long as the process, which ends with its thread still waiting for ticks.@@ -106,6 +73,7 @@ RenderClock::RenderClock(): m_thread(Threading::Thread::construct("RenderClock"sv, [this] {return thread_main();}))+ , m_lanes(*RustFFI::render_clock_lanes_create()){m_thread->start();MutexLocker locker(m_mutex);@@ -181,13 +149,16 @@ ErrorOr<void> RenderClock::replace_channel(IPC::TransportHandle handle)drop_channel();auto transport = TRY(handle.create_transport());m_channel = adopt_ref(*new RenderClockChannel(move(transport), *this));+ m_poster_of_channel = IPC::ThreadSafeMessagePoster::create(m_channel->transport());+ RustFFI::render_clock_lanes_replace_channel(&m_lanes, m_poster_of_channel->to_ffi_with_one_reference());return {};}void RenderClock::drop_channel(){- m_armed_contexts.clear();- m_pointer_lanes.clear();+ RustFFI::render_clock_lanes_drop_channel(&m_lanes);+ if (auto poster = move(m_poster_of_channel))+ poster->detach_from_transport();if (auto channel = move(m_channel)) {channel->detach();channel->shutdown();@@ -198,17 +169,7 @@ void RenderClock::arm_lane(Web::CompositorContextId context_id, double maximum_f{VERIFY(isfinite(maximum_frames_per_second) && maximum_frames_per_second > 0);auto arm = [this, context_id, maximum_frames_per_second, ticks = move(ticks), tick_now_at]() mutable {- // Another document of the context hears of the pointer no more, and a tick armed for it would hand its ticks to- // this one's.- if (auto it = m_pointer_lanes.find(context_id); it != m_pointer_lanes.end() && !it->value.ticks->hands_on_to(*ticks))- m_armed_contexts.remove(context_id);- // The display ticks of an armed context drive its ticks at their rate, however many tasks begin meanwhile.- if (tick_now_at.has_value() && !m_armed_contexts.contains(context_id)) {- (void)ticks->tick(*tick_now_at, {});- m_armed_contexts.set(context_id, ArmedContext { maximum_frames_per_second, ticks });- request_clock_tick(context_id, maximum_frames_per_second);- }- m_pointer_lanes.set(context_id, PointerLane { maximum_frames_per_second, move(ticks) });+ RustFFI::render_clock_lanes_arm_lane(&m_lanes, context_id.value(), maximum_frames_per_second, ticks->ticks(), tick_now_at.has_value(), tick_now_at.value_or(0));};// A test hands the lanes pointer moves by hand, which find the context armed once the rendering update is over.if (m_manual_for_testing)@@ -220,8 +181,7 @@ void RenderClock::arm_lane(Web::CompositorContextId context_id, double maximum_fvoid RenderClock::forget_context(Web::CompositorContextId context_id){(void)invoke_on_clock_thread([this, context_id] {- m_armed_contexts.remove(context_id);- m_pointer_lanes.remove(context_id);+ RustFFI::render_clock_lanes_forget_context(&m_lanes, context_id.value());});}@@ -246,13 +206,14 @@ void RenderClock::run_on_clock_thread_and_wait(Function<void()> job)void RenderClock::disarm_all_for_testing(){- run_on_clock_thread_and_wait([this] { m_armed_contexts.clear(); });+ run_on_clock_thread_and_wait([this] { RustFFI::render_clock_lanes_disarm_all(&m_lanes); });}void RenderClock::hand_pointer_move(Web::CompositorContextId context_id, Optional<Gfx::FloatPoint> device_position, u32 buttons, bool scrolled_since_frame, u64 input_event_id){auto pointer_move = [this, context_id, device_position, buttons, scrolled_since_frame, input_event_id] {- did_receive_pointer_move(context_id, device_position, buttons, scrolled_since_frame, input_event_id);+ auto position = device_position.value_or({});+ RustFFI::render_clock_lanes_pointer_moved(&m_lanes, context_id.value(), device_position.has_value(), position.x(), position.y(), buttons, scrolled_since_frame, input_event_id, m_manual_for_testing);};if (m_manual_for_testing)run_on_clock_thread_and_wait(move(pointer_move));@@ -260,66 +221,11 @@ void RenderClock::hand_pointer_move(Web::CompositorContextId context_id, Optiona(void)invoke_on_clock_thread(move(pointer_move));}-void RenderClock::did_receive_pointer_move(Web::CompositorContextId context_id, Optional<Gfx::FloatPoint> device_position, u32 buttons, bool scrolled_since_frame, u64 input_event_id)-{- auto it = m_pointer_lanes.find(context_id);- if (it == m_pointer_lanes.end())- return;- arm_lane_for_pointer_answer(context_id, it->value, it->value.ticks->pointer_moved(device_position, buttons, scrolled_since_frame, input_event_id));-}--void RenderClock::did_receive_pointer_rest(Web::CompositorContextId context_id)-{- auto it = m_pointer_lanes.find(context_id);- if (it == m_pointer_lanes.end())- return;- arm_lane_for_pointer_answer(context_id, it->value, it->value.ticks->pointer_rests_on_moving_content());-}--void RenderClock::arm_lane_for_pointer_answer(Web::CompositorContextId context_id, PointerLane const& lane, PointerAnswer answer)-{- switch (answer) {- case PointerAnswer::Moves:- return;- case PointerAnswer::Ticks:- break;- }- // A test ticks the lanes by hand.- if (m_manual_for_testing)- return;- // A context armed for ticks already asked for the next one.- if (m_armed_contexts.contains(context_id))- return;- m_armed_contexts.set(context_id, ArmedContext { lane.maximum_frames_per_second, lane.ticks });- request_clock_tick(context_id, lane.maximum_frames_per_second);-}--void RenderClock::request_clock_tick(Web::CompositorContextId context_id, double maximum_frames_per_second)-{- if (m_channel)- m_channel->async_request_clock_tick(context_id, maximum_frames_per_second);-}--void RenderClock::did_receive_clock_tick(Web::CompositorContextId context_id, i64 frame_time_nanoseconds, ReadonlySpan<Web::CompositorScrollOffset> scroll_offsets)-{- // A tick for a context disarmed after its request went out, or armed on an earlier channel.- auto it = m_armed_contexts.find(context_id);- if (it == m_armed_contexts.end())- return;-- // Handing a tick on only queues it, so the next request goes out right after: however long this tick takes, the next- // one is already on its way, and the Compositor's pacing is the only limit on the rate.- if (!it->value.ticks->tick(frame_time_nanoseconds, scroll_offsets)) {- m_armed_contexts.remove(it);- return;- }- request_clock_tick(context_id, it->value.maximum_frames_per_second);-}-void RenderClock::did_lose_channel(){- m_armed_contexts.clear();- m_pointer_lanes.clear();+ RustFFI::render_clock_lanes_drop_channel(&m_lanes);+ if (auto poster = move(m_poster_of_channel))+ poster->detach_from_transport();// The channel is dying from inside its own handler, which keeps it alive until it returns.m_channel = nullptr;}diff --git a/Libraries/LibWeb/Compositor/RenderClock.h b/Libraries/LibWeb/Compositor/RenderClock.hindex 610c9216c74..1a53e783fa9 100644--- a/Libraries/LibWeb/Compositor/RenderClock.h+++ b/Libraries/LibWeb/Compositor/RenderClock.h@@ -9,7 +9,6 @@#include <AK/Atomic.h>#include <AK/ConditionVariable.h>#include <AK/Function.h>-#include <AK/HashMap.h>#include <AK/Mutex.h>#include <AK/NonnullOwnPtr.h>#include <AK/Optional.h>@@ -17,10 +16,10 @@#include <AK/RefPtr.h>#include <LibCore/Forward.h>#include <LibGfx/Point.h>+#include <LibIPC/ThreadSafeMessagePoster.h>#include <LibIPC/TransportHandle.h>#include <LibThreading/Forward.h>#include <LibWeb/Export.h>-#include <LibWebCommon/Page/AsyncScrollNodeStableID.h>#include <LibWebCommon/Page/CompositorContextId.h>namespace Web::Layout::RustFFI {@@ -29,18 +28,16 @@ struct ClockTicks;}+namespace Web::Compositor::RustFFI {++struct RenderClockLanes;++}+namespace Web::Compositor {class RenderClockChannel;-// What a document's clock lanes want once they heard where the pointer went.-enum class PointerAnswer : u8 {- // The moves that follow, but no display tick: no lane hovers the move.- Moves = 1,- // Display ticks too, until a tick declines the next one.- Ticks = 2,-};-// A reference to the ticks of a document's clock lanes, which hands them on to the lane that follows the frame the// document presented last.class WEB_API ClockTicksHandle : public RefCounted<ClockTicksHandle> {@@ -53,18 +50,7 @@ public:}~ClockTicksHandle();- // Hands the lane a tick, with where the Compositor had scrolled to then, and answers whether it wants the next one.- bool tick(i64 frame_time_nanoseconds, ReadonlySpan<Web::CompositorScrollOffset>) const;-- // Hands the lane where the pointer went, or that it left, with the input event id of the mouse event the main thread- // takes beside it, and answers what the lanes want next.- PointerAnswer pointer_moved(Optional<Gfx::FloatPoint> device_position, u32 buttons, bool scrolled_since_frame, u64 input_event_id) const;-- // Hands the lane that the pointer rests where the Compositor's animations move what is under it, which the next- // tick hovers again, and answers what the lanes want next.- PointerAnswer pointer_rests_on_moving_content() const;-- bool hands_on_to(ClockTicksHandle const& other) const { return m_ticks == other.m_ticks; }+ Layout::RustFFI::ClockTicks const* ticks() const { return m_ticks; }private:Layout::RustFFI::ClockTicks const* m_ticks { nullptr };@@ -114,11 +100,6 @@ public:bool is_manual_for_testing() const { return m_manual_for_testing; }private:- struct ArmedContext {- double maximum_frames_per_second { 60.0 };- NonnullRefPtr<ClockTicksHandle> ticks;- };-friend class RenderClockChannel;RenderClock();@@ -129,10 +110,6 @@ private:// On the clock thread.ErrorOr<void> replace_channel(IPC::TransportHandle);void drop_channel();- void request_clock_tick(Web::CompositorContextId, double maximum_frames_per_second);- void did_receive_clock_tick(Web::CompositorContextId, i64 frame_time_nanoseconds, ReadonlySpan<Web::CompositorScrollOffset>);- void did_receive_pointer_move(Web::CompositorContextId, Optional<Gfx::FloatPoint> device_position, u32 buttons, bool scrolled_since_frame, u64 input_event_id);- void did_receive_pointer_rest(Web::CompositorContextId);void did_lose_channel();NonnullRefPtr<Threading::Thread> m_thread;@@ -145,13 +122,8 @@ private:// Owned by the clock thread.RefPtr<RenderClockChannel> m_channel;- HashMap<Web::CompositorContextId, ArmedContext> m_armed_contexts;- struct PointerLane {- double maximum_frames_per_second { 60.0 };- NonnullRefPtr<ClockTicksHandle> ticks;- };- HashMap<Web::CompositorContextId, PointerLane> m_pointer_lanes;- void arm_lane_for_pointer_answer(Web::CompositorContextId, PointerLane const&, PointerAnswer);+ RefPtr<IPC::ThreadSafeMessagePoster> m_poster_of_channel;+ RustFFI::RenderClockLanes& m_lanes;};}diff --git a/Libraries/LibWeb/Rust/Cargo.toml b/Libraries/LibWeb/Rust/Cargo.tomlindex 07cd9444e84..ec7805ff64f 100644--- a/Libraries/LibWeb/Rust/Cargo.toml+++ b/Libraries/LibWeb/Rust/Cargo.toml@@ -20,6 +20,7 @@ hashbrown = "0.17.1"ladybird_allocator = { path = "../../RustAllocator", optional = true }libcompositing_rust = { path = "../../LibCompositing/Rust" }libgfx_rust = { path = "../../LibGfx/Rust", default-features = false }+libipc_rust = { path = "../../LibIPC/Rust" }liburl_rust = { path = "../../LibURL/Rust", default-features = false }libweb_html_tokenizer = { path = "../HTML/Parser/Rust" }rayon = "1.12"diff --git a/Libraries/LibWeb/Rust/build.rs b/Libraries/LibWeb/Rust/build.rsindex 00ff91fa797..add81469527 100644--- a/Libraries/LibWeb/Rust/build.rs+++ b/Libraries/LibWeb/Rust/build.rs@@ -3070,6 +3070,36 @@ fn main() -> Result<(), Box<dyn Error>> {Path::new("Layout/TreeBuilderRustFFI.h"),);+ // The lanes of the render clock - namespace Web::Compositor::RustFFI, layered on the layout header for the ticks+ // the lanes hand on.+ let mut render_clock_config = base_config.clone();+ render_clock_config.namespaces = Some(vec!["Web".to_string(), "Compositor".to_string(), "RustFFI".to_string()]);+ for (rust_name, cpp_name) in [+ ("ArcRef", "Web::Layout::RustFFI::ArcRef"),+ ("ClockTicks", "Web::Layout::RustFFI::ClockTicks"),+ ("FfiThreadSafeMessagePoster", "IPC::FfiThreadSafeMessagePoster"),+ ("RawMessage", "IPC::FfiRawMessage"),+ ] {+ render_clock_config+ .export+ .rename+ .insert(rust_name.to_string(), cpp_name.to_string());+ }+ render_clock_config.includes.extend(+ [+ "LibIPC/RawMessage.h",+ "LibIPC/ThreadSafeMessagePoster.h",+ "LibWeb/Layout/LayoutRustFFI.h",+ ]+ .map(String::from),+ );+ generate_ffi_header(+ render_clock_config,+ &[manifest_dir.join("src/render_state/clock/render_clock.rs")],+ &out_dir,+ Path::new("Compositor/RenderClockRustFFI.h"),+ );+// Layout engine header - namespace Web::Layout::RustFFI, layered on the tree-builder// header.let mut layout_config = base_config;diff --git a/Libraries/LibWeb/Rust/src/render_state/clock.rs b/Libraries/LibWeb/Rust/src/render_state/clock.rsindex cc7ab5bc7aa..13811347330 100644--- a/Libraries/LibWeb/Rust/src/render_state/clock.rs+++ b/Libraries/LibWeb/Rust/src/render_state/clock.rs@@ -64,6 +64,7 @@ use std::sync::{Arc, Mutex};mod effects;pub(crate) mod hover;mod lane;+mod render_clock;mod selection;pub(crate) use hover::PendingPointer;pub(crate) use lane::LaneDelivery;@@ -1893,17 +1894,6 @@ impl ClockRecorder {}}-/// Hands the lanes `ticks` belong to a display tick at `frame_time_nanoseconds`, at which the compositor had scrolled to-/// the offsets `scroll_offsets`, and answers whether they want the next one.-#[unsafe(no_mangle)]-pub extern "C" fn clock_ticks_tick(- ticks: crate::css::ffi_support::ArcRef<'_, ClockTicks>,- frame_time_nanoseconds: i64,- scroll_offsets: ak::Span<'_, FfiScrollOffset>,-) -> bool {- ticks.to_arc().tick(frame_time_nanoseconds, scroll_offsets.as_slice())-}-/// Gives up the reference `ticks` holds.#[unsafe(no_mangle)]pub extern "C" fn clock_ticks_release(ticks: OwnedArc<ClockTicks>) {diff --git a/Libraries/LibWeb/Rust/src/render_state/clock/hover.rs b/Libraries/LibWeb/Rust/src/render_state/clock/hover.rsindex 1adbbd741ff..3c4ec14b2fa 100644--- a/Libraries/LibWeb/Rust/src/render_state/clock/hover.rs+++ b/Libraries/LibWeb/Rust/src/render_state/clock/hover.rs@@ -1698,36 +1698,6 @@ fn cursor_for_hit(state: &mut RenderState, hit: CursorHit) -> Option<u8> {})}-/// Hands the clock lane `ticks` belong to where the pointer went: to `x`, `y` in device pixels where `has_position`,-/// or out of the context, beside the mouse event with the input event id `input_event_id`, and answers what the lane-/// wants next, as a `PointerAnswer`.-///-#[unsafe(no_mangle)]-pub extern "C" fn clock_ticks_pointer_moved(- ticks: &super::ClockTicks,- has_position: bool,- x: f32,- y: f32,- buttons: u32,- scrolled_since_frame: bool,- input_event_id: u64,-) -> u8 {- ticks.pointer_moved(PendingPointer {- position: has_position.then_some(FloatPoint { x, y }),- buttons,- scrolled_since_frame,- input_event_id,- }) as u8-}--/// Hands the clock lane `ticks` belong to that the pointer rests where the compositor's animations move what is under-/// it, which the next tick hovers again in the frame as the screen shows it, and answers what the lane wants next, as a-/// `PointerAnswer`.-#[unsafe(no_mangle)]-pub extern "C" fn clock_ticks_pointer_rests_on_moving_content(ticks: &super::ClockTicks) -> u8 {- ticks.pointer_rests_on_moving_content() as u8-}-/// Hands the clock lanes of `host`'s document that the pointer rests where the compositor's animations move what is/// under it, ticks them at `frame_time_nanoseconds`, and waits as [`document_host_inject_pointer`] does. For a test.#[unsafe(no_mangle)]diff --git a/Libraries/LibWeb/Rust/src/render_state/clock/render_clock.rs b/Libraries/LibWeb/Rust/src/render_state/clock/render_clock.rsnew file mode 100644index 00000000000..304e66b3da2--- /dev/null+++ b/Libraries/LibWeb/Rust/src/render_state/clock/render_clock.rs@@ -0,0 +1,349 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What the render clock's thread keeps of the contexts it hands display ticks and pointer moves on for, and what it+//! makes of the messages of the render clock channel. `Web::Compositor::RenderClock` owns it, and only reaches it on+//! the clock thread.++use super::hover::{PendingPointer, PointerAnswer};+use super::{ClockTicks, FfiScrollOffset};+use crate::css::ffi_support::ArcRef;+use libcompositing_rust::display_list::commands::CompositorContextId;+use libcompositing_rust::ipc_types::{Web_AsyncScrollNodeKind, Web_CompositorScrollOffset};+use libcompositing_rust::ipc_types::{render_clock_client, render_clock_server};+use libgfx_rust::FloatPoint;+use libipc_rust::Misbehavior;+use libipc_rust::cpp_connection::{FfiThreadSafeMessagePoster, RawMessage, ThreadSafeMessagePoster};+use std::collections::HashMap;+use std::sync::Arc;++struct ArmedContext {+ maximum_frames_per_second: f64,+ ticks: Arc<ClockTicks>,+}++struct PointerLane {+ maximum_frames_per_second: f64,+ ticks: Arc<ClockTicks>,+}++#[derive(Clone, Copy, PartialEq, Eq)]+enum LanesAreTicked {+ ByDisplayTicks,+ ByHandForATest,+}++#[derive(Default)]+pub struct RenderClockLanes {+ channel_to_compositor: Option<ThreadSafeMessagePoster>,+ armed_contexts: HashMap<CompositorContextId, ArmedContext>,+ pointer_lanes: HashMap<CompositorContextId, PointerLane>,+}++impl RenderClockLanes {+ fn replace_channel(&mut self, channel_to_compositor: ThreadSafeMessagePoster) {+ // A new channel starts with nothing armed: the contexts armed on the previous one were armed for a Compositor+ // that is gone.+ self.drop_channel();+ self.channel_to_compositor = Some(channel_to_compositor);+ }++ fn drop_channel(&mut self) {+ self.armed_contexts.clear();+ self.pointer_lanes.clear();+ self.channel_to_compositor = None;+ }++ fn arm_lane(+ &mut self,+ context_id: CompositorContextId,+ maximum_frames_per_second: f64,+ ticks: Arc<ClockTicks>,+ tick_now_at: Option<i64>,+ ) {+ // Another document of the context hears of the pointer no more, and a tick armed for it would hand its ticks to+ // this one's.+ if self+ .pointer_lanes+ .get(&context_id)+ .is_some_and(|lane| !Arc::ptr_eq(&lane.ticks, &ticks))+ {+ self.armed_contexts.remove(&context_id);+ }+ // The display ticks of an armed context drive its ticks at their rate, however many tasks begin meanwhile.+ if let Some(tick_now_at) = tick_now_at+ && !self.armed_contexts.contains_key(&context_id)+ {+ let _ = ticks.tick(tick_now_at, &[]);+ self.armed_contexts.insert(+ context_id,+ ArmedContext {+ maximum_frames_per_second,+ ticks: Arc::clone(&ticks),+ },+ );+ self.request_clock_tick(context_id, maximum_frames_per_second);+ }+ self.pointer_lanes.insert(+ context_id,+ PointerLane {+ maximum_frames_per_second,+ ticks,+ },+ );+ }++ fn forget_context(&mut self, context_id: CompositorContextId) {+ self.armed_contexts.remove(&context_id);+ self.pointer_lanes.remove(&context_id);+ }++ fn pointer_moved(+ &mut self,+ context_id: CompositorContextId,+ pointer: PendingPointer,+ lanes_are_ticked: LanesAreTicked,+ ) {+ let Some(lane) = self.pointer_lanes.get(&context_id) else {+ return;+ };+ let answer = lane.ticks.pointer_moved(pointer);+ self.arm_lane_for_pointer_answer(context_id, answer, lanes_are_ticked);+ }++ fn pointer_rests_on_moving_content(&mut self, context_id: CompositorContextId, lanes_are_ticked: LanesAreTicked) {+ let Some(lane) = self.pointer_lanes.get(&context_id) else {+ return;+ };+ let answer = lane.ticks.pointer_rests_on_moving_content();+ self.arm_lane_for_pointer_answer(context_id, answer, lanes_are_ticked);+ }++ fn arm_lane_for_pointer_answer(+ &mut self,+ context_id: CompositorContextId,+ answer: PointerAnswer,+ lanes_are_ticked: LanesAreTicked,+ ) {+ match answer {+ PointerAnswer::Moves => return,+ PointerAnswer::Ticks => {}+ }+ // A test ticks the lanes by hand.+ if lanes_are_ticked == LanesAreTicked::ByHandForATest {+ return;+ }+ // A context armed for ticks already asked for the next one.+ if self.armed_contexts.contains_key(&context_id) {+ return;+ }+ let Some(lane) = self.pointer_lanes.get(&context_id) else {+ return;+ };+ let maximum_frames_per_second = lane.maximum_frames_per_second;+ self.armed_contexts.insert(+ context_id,+ ArmedContext {+ maximum_frames_per_second,+ ticks: Arc::clone(&lane.ticks),+ },+ );+ self.request_clock_tick(context_id, maximum_frames_per_second);+ }++ fn request_clock_tick(&self, context_id: CompositorContextId, maximum_frames_per_second: f64) {+ if let Some(channel_to_compositor) = &self.channel_to_compositor {+ let _ = channel_to_compositor.try_post(render_clock_server::messages::RequestClockTick {+ context_id,+ maximum_frames_per_second,+ });+ }+ }++ fn clock_tick(+ &mut self,+ context_id: CompositorContextId,+ frame_time_nanoseconds: i64,+ scroll_offsets: &[Web_CompositorScrollOffset],+ ) {+ // A tick for a context disarmed after its request went out, or armed on an earlier channel.+ let Some(armed_context) = self.armed_contexts.get(&context_id) else {+ return;+ };++ // A scroll timeline follows the scroll node of an element or a document's viewport, which its unique id names.+ let scrollers: Vec<FfiScrollOffset> = scroll_offsets+ .iter()+ .filter(|scroll_offset| scroll_offset.scroll_node.kind != Web_AsyncScrollNodeKind::PseudoElement)+ .map(|scroll_offset| FfiScrollOffset {+ scroller: scroll_offset.scroll_node.node_id.0,+ x: scroll_offset.offset.x.to_double(),+ y: scroll_offset.offset.y.to_double(),+ })+ .collect();++ // Handing a tick on only queues it, so the next request goes out right after: however long this tick takes,+ // the next one is already on its way, and the Compositor's pacing is the only limit on the rate.+ if !armed_context.ticks.tick(frame_time_nanoseconds, &scrollers) {+ self.armed_contexts.remove(&context_id);+ return;+ }+ let maximum_frames_per_second = armed_context.maximum_frames_per_second;+ self.request_clock_tick(context_id, maximum_frames_per_second);+ }+}++struct MessagesFromCompositor<'a> {+ lanes: &'a mut RenderClockLanes,+ lanes_are_ticked: LanesAreTicked,+}++impl render_clock_client::Stub for MessagesFromCompositor<'_> {+ fn clock_tick(&mut self, tick: render_clock_client::messages::ClockTick) -> Result<(), Misbehavior> {+ self.lanes+ .clock_tick(tick.context_id, tick.frame_time_nanoseconds, &tick.scroll_offsets);+ Ok(())+ }++ fn pointer_moved(&mut self, moved: render_clock_client::messages::PointerMoved) -> Result<(), Misbehavior> {+ self.lanes.pointer_moved(+ moved.context_id,+ PendingPointer {+ position: Some(FloatPoint {+ x: moved.position.x as f32,+ y: moved.position.y as f32,+ }),+ buttons: moved.buttons,+ scrolled_since_frame: moved.scrolled_since_frame,+ input_event_id: moved.input_event_id,+ },+ self.lanes_are_ticked,+ );+ Ok(())+ }++ fn pointer_left(&mut self, left: render_clock_client::messages::PointerLeft) -> Result<(), Misbehavior> {+ self.lanes.pointer_moved(+ left.context_id,+ PendingPointer {+ position: None,+ buttons: 0,+ scrolled_since_frame: false,+ input_event_id: left.input_event_id,+ },+ self.lanes_are_ticked,+ );+ Ok(())+ }++ fn pointer_rests_on_moving_content(+ &mut self,+ rests: render_clock_client::messages::PointerRestsOnMovingContent,+ ) -> Result<(), Misbehavior> {+ self.lanes+ .pointer_rests_on_moving_content(rests.context_id, self.lanes_are_ticked);+ Ok(())+ }+}++fn lanes_are_ticked(by_hand_for_a_test: bool) -> LanesAreTicked {+ if by_hand_for_a_test {+ LanesAreTicked::ByHandForATest+ } else {+ LanesAreTicked::ByDisplayTicks+ }+}++/// The lanes of the process's render clock, which lives as long as the process.+#[unsafe(no_mangle)]+pub extern "C" fn render_clock_lanes_create() -> *mut RenderClockLanes {+ Box::into_raw(Box::default())+}++/// # Safety+///+/// `channel_to_compositor` must hold one reference to a live `IPC::ThreadSafeMessagePoster`, which the caller gives up.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn render_clock_lanes_replace_channel(+ lanes: &mut RenderClockLanes,+ channel_to_compositor: FfiThreadSafeMessagePoster,+) {+ // SAFETY: The caller gives up the reference the poster holds.+ lanes.replace_channel(unsafe { ThreadSafeMessagePoster::adopt(channel_to_compositor) });+}++#[unsafe(no_mangle)]+pub extern "C" fn render_clock_lanes_drop_channel(lanes: &mut RenderClockLanes) {+ lanes.drop_channel();+}++#[unsafe(no_mangle)]+pub extern "C" fn render_clock_lanes_arm_lane(+ lanes: &mut RenderClockLanes,+ context_id: u64,+ maximum_frames_per_second: f64,+ ticks: ArcRef<'_, ClockTicks>,+ ticks_now: bool,+ tick_now_at: i64,+) {+ lanes.arm_lane(+ CompositorContextId(context_id),+ maximum_frames_per_second,+ ticks.to_arc(),+ ticks_now.then_some(tick_now_at),+ );+}++#[unsafe(no_mangle)]+pub extern "C" fn render_clock_lanes_forget_context(lanes: &mut RenderClockLanes, context_id: u64) {+ lanes.forget_context(CompositorContextId(context_id));+}++#[unsafe(no_mangle)]+pub extern "C" fn render_clock_lanes_disarm_all(lanes: &mut RenderClockLanes) {+ lanes.armed_contexts.clear();+}++#[unsafe(no_mangle)]+pub extern "C" fn render_clock_lanes_pointer_moved(+ lanes: &mut RenderClockLanes,+ context_id: u64,+ has_position: bool,+ x: f32,+ y: f32,+ buttons: u32,+ scrolled_since_frame: bool,+ input_event_id: u64,+ lanes_are_ticked_by_hand_for_a_test: bool,+) {+ lanes.pointer_moved(+ CompositorContextId(context_id),+ PendingPointer {+ position: has_position.then_some(FloatPoint { x, y }),+ buttons,+ scrolled_since_frame,+ input_event_id,+ },+ lanes_are_ticked(lanes_are_ticked_by_hand_for_a_test),+ );+}++/// # Safety+///+/// `message` must be one `IPC::RawMessage::hand_to_rust()` made.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn render_clock_lanes_handle_message(+ lanes: &mut RenderClockLanes,+ message: RawMessage<'_>,+ lanes_are_ticked_by_hand_for_a_test: bool,+) {+ let mut stub = MessagesFromCompositor {+ lanes,+ lanes_are_ticked: lanes_are_ticked(lanes_are_ticked_by_hand_for_a_test),+ };+ // SAFETY: The caller hands over a message of the render clock channel.+ unsafe { message.hand_to(|bytes, attachments| render_clock_client::dispatch(&mut stub, bytes, attachments)) };+}diff --git a/Services/Compositor/RenderClockClient.ipc b/Services/Compositor/RenderClockClient.ipcindex 91261ee4839..83b49a73311 100644--- a/Services/Compositor/RenderClockClient.ipc+++ b/Services/Compositor/RenderClockClient.ipc@@ -5,14 +5,14 @@endpoint RenderClockClient{// With where the compositor has scrolled the context's scroll nodes to at the tick.- clock_tick(Web::CompositorContextId context_id, i64 frame_time_nanoseconds, double frame_interval_milliseconds, Vector<Web::CompositorScrollOffset> scroll_offsets) =|+ [RustReceiver] clock_tick(Web::CompositorContextId context_id, i64 frame_time_nanoseconds, double frame_interval_milliseconds, Vector<Web::CompositorScrollOffset> scroll_offsets) =|// The pointer moved to `position`, in the context's device pixels, beside the mouse event the main thread takes,// whose input event id `input_event_id` is. `buttons` are the buttons held, and `scrolled_since_frame` says whether// the compositor scrolled the context since the last frame WebContent presented, whose scroll offsets a hit test// there would not know.- pointer_moved(Web::CompositorContextId context_id, Web::DevicePixelPoint position, u32 buttons, bool scrolled_since_frame, u64 input_event_id) =|+ [RustReceiver] pointer_moved(Web::CompositorContextId context_id, Web::DevicePixelPoint position, u32 buttons, bool scrolled_since_frame, u64 input_event_id) =|// The pointer left the context, beside the mouse event with the input event id `input_event_id`.- pointer_left(Web::CompositorContextId context_id, u64 input_event_id) =|- pointer_rests_on_moving_content(Web::CompositorContextId context_id) =|+ [RustReceiver] pointer_left(Web::CompositorContextId context_id, u64 input_event_id) =|+ [RustReceiver] pointer_rests_on_moving_content(Web::CompositorContextId context_id) =|}diff --git a/Services/Compositor/RenderClockServer.ipc b/Services/Compositor/RenderClockServer.ipcindex 7cd430ca4c8..27fc0203e48 100644--- a/Services/Compositor/RenderClockServer.ipc+++ b/Services/Compositor/RenderClockServer.ipc@@ -3,5 +3,5 @@endpoint RenderClockServer{// One-shot, like a rendering opportunity: the context gets the next display tick its maximum rate lets through.- request_clock_tick(Web::CompositorContextId context_id, double maximum_frames_per_second) =|+ [RustSender] request_clock_tick(Web::CompositorContextId context_id, double maximum_frames_per_second) =|}