Truly independent web browser
LibWeb: Implement VisualViewport in Rust
Andreas Klingba89bb7a7516
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/css/exports.rsindex 0ecf1265c7c..cd3d3ac3e22 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs@@ -13,6 +13,7 @@ use std::rc::Rc;use std::sync::Arc;use ak::Utf16String;+use libcompositing_rust::css_pixels::{CssPixelRect, FfiCssPixelPoint, FfiCssPixelRect};use libjs_rust::api::{Gc, MarkedVec, Vm};use libweb_rust::typed_om::{FfiNumericType, RetainedStyleValue};use libweb_rust::{NativeMediaList, NativeRule, NativeRuleList};@@ -66,6 +67,7 @@ use super::style_property_map_read_only::StylePropertyMapReadOnly;use super::style_sheet_list::StyleSheetList;use super::transition_event::{TransitionEvent, TransitionEventInit};use super::typed_om;+use super::visual_viewport::VisualViewport;use crate::bindings::conversions::CppInterface;use crate::bindings::cpp_cell::CppCell;use crate::bindings::interface::{Ref, allocate, cell_from_abi, cell_if_abi, cell_into_abi, realm_arguments};@@ -1011,3 +1013,203 @@ pub unsafe extern "C" fn web_css_style_sheet_list_create(let (vm, node) = unsafe { (vm_from_abi(vm), CppCell::from_raw(node)) };cell_into_abi(allocate(vm, |_| StyleSheetList::new(scope, node)))}++/// A new VisualViewport of the document.+///+/// # Safety+///+/// `vm` must be the live VM, `realm` a live realm, and `document` a live document.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_visual_viewport_create(+ vm: *mut c_void,+ realm: *mut c_void,+ document: *mut c_void,+) -> *mut c_void {+ // SAFETY: The caller passes the live VM, a live realm and a live document.+ let (vm, realm, document) = unsafe {+ let (vm, realm) = realm_arguments(vm, realm);+ (vm, realm, CppCell::from_raw(document))+ };+ cell_into_abi(VisualViewport::create(vm, realm, document))+}++/// # Safety+///+/// `viewport` must be a live VisualViewport.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_visual_viewport_event_target(viewport: *mut c_void) -> *mut c_void {+ // SAFETY: The caller passes a live VisualViewport.+ unsafe { cell_from_abi::<VisualViewport>(viewport) }+ .event_target()+ .as_ptr()+}++/// # Safety+///+/// `viewport` must be a live VisualViewport.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_visual_viewport_offset(viewport: *mut c_void) -> FfiCssPixelPoint {+ // SAFETY: The caller passes a live VisualViewport.+ unsafe { cell_from_abi::<VisualViewport>(viewport) }.offset().into()+}++/// # Safety+///+/// `viewport` must be a live VisualViewport.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_visual_viewport_offset_left(viewport: *mut c_void) -> f64 {+ // SAFETY: The caller passes a live VisualViewport.+ unsafe { cell_from_abi::<VisualViewport>(viewport) }.offset_left_value()+}++/// # Safety+///+/// `viewport` must be a live VisualViewport.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_visual_viewport_offset_top(viewport: *mut c_void) -> f64 {+ // SAFETY: The caller passes a live VisualViewport.+ unsafe { cell_from_abi::<VisualViewport>(viewport) }.offset_top_value()+}++/// # Safety+///+/// `viewport` must be a live VisualViewport.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_visual_viewport_page_left(viewport: *mut c_void) -> f64 {+ // SAFETY: The caller passes a live VisualViewport.+ unsafe { cell_from_abi::<VisualViewport>(viewport) }.page_left_value()+}++/// # Safety+///+/// `viewport` must be a live VisualViewport.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_visual_viewport_page_top(viewport: *mut c_void) -> f64 {+ // SAFETY: The caller passes a live VisualViewport.+ unsafe { cell_from_abi::<VisualViewport>(viewport) }.page_top_value()+}++/// # Safety+///+/// `viewport` must be a live VisualViewport.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_visual_viewport_width(viewport: *mut c_void) -> f64 {+ // SAFETY: The caller passes a live VisualViewport.+ unsafe { cell_from_abi::<VisualViewport>(viewport) }.width_value()+}++/// # Safety+///+/// `viewport` must be a live VisualViewport.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_visual_viewport_height(viewport: *mut c_void) -> f64 {+ // SAFETY: The caller passes a live VisualViewport.+ unsafe { cell_from_abi::<VisualViewport>(viewport) }.height_value()+}++/// # Safety+///+/// `viewport` must be a live VisualViewport.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_visual_viewport_scale(viewport: *mut c_void) -> f64 {+ // SAFETY: The caller passes a live VisualViewport.+ unsafe { cell_from_abi::<VisualViewport>(viewport) }.scale_value()+}++/// # Safety+///+/// `viewport` must be a live VisualViewport.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_visual_viewport_scroll_by(viewport: *mut c_void, delta: FfiCssPixelPoint) {+ // SAFETY: The caller passes a live VisualViewport.+ unsafe { cell_from_abi::<VisualViewport>(viewport) }.scroll_by(delta.into());+}++/// # Safety+///+/// `viewport` must be a live VisualViewport.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_visual_viewport_zoom(viewport: *mut c_void, position: FfiCssPixelPoint, scale_delta: f64) {+ // SAFETY: The caller passes a live VisualViewport.+ unsafe { cell_from_abi::<VisualViewport>(viewport) }.zoom(position.into(), scale_delta);+}++/// # Safety+///+/// `viewport` must be a live VisualViewport.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_visual_viewport_set_scale_zoomed_by_compositor(viewport: *mut c_void, scale: f64) {+ // SAFETY: The caller passes a live VisualViewport.+ unsafe { cell_from_abi::<VisualViewport>(viewport) }.set_scale_zoomed_by_compositor(scale);+}++/// Whether the scale changed since the compositor last heard of it, in which case `scale` receives it.+///+/// # Safety+///+/// `viewport` must be a live VisualViewport.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_visual_viewport_take_scale_for_compositor(viewport: *mut c_void, scale: &mut f64) -> bool {+ // SAFETY: The caller passes a live VisualViewport.+ let taken = unsafe { cell_from_abi::<VisualViewport>(viewport) }.take_scale_for_compositor();+ if let Some(taken) = taken {+ *scale = taken;+ }+ taken.is_some()+}++/// # Safety+///+/// `viewport` must be a live VisualViewport.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_visual_viewport_map_to_layout_viewport(+ viewport: *mut c_void,+ position: FfiCssPixelPoint,+) -> FfiCssPixelPoint {+ // SAFETY: The caller passes a live VisualViewport.+ unsafe { cell_from_abi::<VisualViewport>(viewport) }+ .map_to_layout_viewport(position.into())+ .into()+}++/// # Safety+///+/// `viewport` must be a live VisualViewport.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_visual_viewport_map_point_from_layout_viewport(+ viewport: *mut c_void,+ position: FfiCssPixelPoint,+) -> FfiCssPixelPoint {+ // SAFETY: The caller passes a live VisualViewport.+ unsafe { cell_from_abi::<VisualViewport>(viewport) }+ .map_point_from_layout_viewport(position.into())+ .into()+}++/// # Safety+///+/// `viewport` must be a live VisualViewport.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_visual_viewport_map_rect_from_layout_viewport(+ viewport: *mut c_void,+ rect: FfiCssPixelRect,+) -> FfiCssPixelRect {+ // SAFETY: The caller passes a live VisualViewport.+ let viewport = unsafe { cell_from_abi::<VisualViewport>(viewport) };+ let mapped = viewport.map_rect_from_layout_viewport(CssPixelRect::new(rect.x, rect.y, rect.width, rect.height));+ FfiCssPixelRect {+ x: mapped.x,+ y: mapped.y,+ width: mapped.width,+ height: mapped.height,+ }+}++/// # Safety+///+/// `viewport` must be a live VisualViewport.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_visual_viewport_reset(viewport: *mut c_void) {+ // SAFETY: The caller passes a live VisualViewport.+ unsafe { cell_from_abi::<VisualViewport>(viewport) }.reset();+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/css/mod.rsindex a85a7efe220..faa53bea0af 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs@@ -82,3 +82,4 @@ pub(crate) mod style_sheet;pub(crate) mod style_sheet_list;pub(crate) mod transition_event;pub(crate) mod typed_om;+pub(crate) mod visual_viewport;diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/visual_viewport.rs b/Libraries/LibWeb/Bindings/Rust/src/css/visual_viewport.rsnew file mode 100644index 00000000000..e10bd67cba4--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/css/visual_viewport.rs@@ -0,0 +1,352 @@+/*+ * Copyright (c) 2023, Andreas Kling <[email protected]>+ * Copyright (c) 2025, Aliaksandr Kalenik <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! VisualViewport, https://drafts.csswg.org/cssom-view/#visualviewport++use core::cell::Cell;+use core::ffi::c_void;+use core::ptr::NonNull;++use libcompositing_rust::css_pixels::{CssPixelPoint, CssPixelRect, CssPixels, FfiCssPixelRect};+use libgfx_rust::geometry::{FloatPoint, FloatRect};+use libgfx_rust::matrix::AffineTransform;+use libjs_rust::api::{Gc, Realm, Trace, Vm};++use crate::bindings::cpp_cell::CppCell;+use crate::bindings::event_target::{CppEventTarget, GetTheParent};+use crate::bindings::interface::{Ref, Wrappable, allocate};+use crate::bindings::{CallContext, WebIdlResult};++unsafe extern "C" {+ fn web_css_visual_viewport_document_is_fully_active(document: *mut c_void) -> bool;+ fn web_css_visual_viewport_document_viewport_rect(document: *mut c_void) -> FfiCssPixelRect;+ fn web_css_visual_viewport_append_pending_scroll_event(+ document: *mut c_void,+ event_target: *mut c_void,+ r#type: ak::Span<'_, u8>,+ );+ fn web_css_visual_viewport_did_change_offset_or_scale(document: *mut c_void);+}++const SCROLL: &str = "scroll";+const SCROLLEND: &str = "scrollend";++const MIN_ALLOWED_SCALE: f64 = 1.0;+const MAX_ALLOWED_SCALE: f64 = 5.0;++// https://drafts.csswg.org/cssom-view/#visualviewport+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct VisualViewport {+ event_target: CppEventTarget,+ realm: Gc<Realm>,+ document: CppCell,++ #[gc(untraced)]+ offset: Cell<CssPixelPoint>,+ #[gc(untraced)]+ scale: Cell<f64>,+ scale_is_new_to_compositor: Cell<bool>,+}++impl Wrappable for VisualViewport {+ fn relevant_realm(&self) -> Option<Gc<Realm>> {+ Some(self.realm)+ }++ fn cpp_parent(&self) -> Option<NonNull<c_void>> {+ self.event_target.as_cpp_parent()+ }+}++impl GetTheParent for VisualViewport {+ fn get_the_parent(&self) -> Option<CppEventTarget> {+ None+ }+}++impl VisualViewport {+ pub(crate) fn create(vm: &Vm, realm: Gc<Realm>, document: CppCell) -> Ref<Self> {+ let object = allocate(vm, |_| VisualViewport {+ event_target: CppEventTarget::new(),+ realm,+ document,+ offset: Cell::new(CssPixelPoint::default()),+ scale: Cell::new(1.0),+ scale_is_new_to_compositor: Cell::new(false),+ });+ object.event_target.set_owner(object);+ object+ }++ pub(crate) fn event_target(&self) -> &CppEventTarget {+ &self.event_target+ }++ pub(crate) fn offset(&self) -> CssPixelPoint {+ self.offset.get()+ }++ fn document_is_fully_active(&self) -> bool {+ // SAFETY: The document is live.+ unsafe { web_css_visual_viewport_document_is_fully_active(self.document.as_ptr()) }+ }++ fn viewport_rect(&self) -> CssPixelRect {+ // SAFETY: The document is live.+ let rect = unsafe { web_css_visual_viewport_document_viewport_rect(self.document.as_ptr()) };+ CssPixelRect::new(rect.x, rect.y, rect.width, rect.height)+ }++ fn append_pending_scroll_event(&self, event_type: &str) {+ // SAFETY: The document and the EventTarget are live, and the type is lent for the call.+ unsafe {+ web_css_visual_viewport_append_pending_scroll_event(+ self.document.as_ptr(),+ self.event_target.as_ptr(),+ ak::Span::new(event_type.as_bytes()),+ );+ }+ }++ // https://drafts.csswg.org/cssom-view/#dom-visualviewport-offsetleft+ pub(crate) fn offset_left_value(&self) -> f64 {+ // 1. If the visual viewport’s associated document is not fully active, return 0.+ if !self.document_is_fully_active() {+ return 0.0;+ }++ // 2. Otherwise, return the offset of the left edge of the visual viewport from the left edge of the layout+ // viewport.+ self.offset.get().x.to_double()+ }++ // https://drafts.csswg.org/cssom-view/#dom-visualviewport-offsettop+ pub(crate) fn offset_top_value(&self) -> f64 {+ // 1. If the visual viewport’s associated document is not fully active, return 0.+ if !self.document_is_fully_active() {+ return 0.0;+ }++ // 2. Otherwise, return the offset of the top edge of the visual viewport from the top edge of the layout+ // viewport.+ self.offset.get().y.to_double()+ }++ // https://drafts.csswg.org/cssom-view/#dom-visualviewport-pageleft+ pub(crate) fn page_left_value(&self) -> f64 {+ // 1. If the visual viewport’s associated document is not fully active, return 0.+ if !self.document_is_fully_active() {+ return 0.0;+ }++ // 2. Otherwise, return the offset of the left edge of the visual viewport from the+ // left edge of the initial containing block of the layout viewport’s document.+ self.viewport_rect().x.to_double() + self.offset_left_value()+ }++ // https://drafts.csswg.org/cssom-view/#dom-visualviewport-pagetop+ pub(crate) fn page_top_value(&self) -> f64 {+ // 1. If the visual viewport’s associated document is not fully active, return 0.+ if !self.document_is_fully_active() {+ return 0.0;+ }++ // 2. Otherwise, return the offset of the top edge of the visual viewport from the+ // top edge of the initial containing block of the layout viewport’s document.+ self.viewport_rect().y.to_double() + self.offset_top_value()+ }++ // https://drafts.csswg.org/cssom-view/#dom-visualviewport-width+ pub(crate) fn width_value(&self) -> f64 {+ // 1. If the visual viewport’s associated document is not fully active, return 0.+ if !self.document_is_fully_active() {+ return 0.0;+ }++ // 2. Otherwise, return the width of the visual viewport+ // FIXME: excluding the width of any rendered vertical classic scrollbar that is fixed to the visual viewport.+ self.viewport_rect().width.to_double() / self.scale.get()+ }++ // https://drafts.csswg.org/cssom-view/#dom-visualviewport-height+ pub(crate) fn height_value(&self) -> f64 {+ // 1. If the visual viewport’s associated document is not fully active, return 0.+ if !self.document_is_fully_active() {+ return 0.0;+ }++ // 2. Otherwise, return the height of the visual viewport+ // FIXME: excluding the height of any rendered vertical classic scrollbar that is fixed to the visual viewport.+ self.viewport_rect().height.to_double() / self.scale.get()+ }++ // https://drafts.csswg.org/cssom-view/#dom-visualviewport-scale+ pub(crate) fn scale_value(&self) -> f64 {+ self.scale.get()+ }++ pub(crate) fn offset_left(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.offset_left_value())+ }++ pub(crate) fn offset_top(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.offset_top_value())+ }++ pub(crate) fn page_left(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.page_left_value())+ }++ pub(crate) fn page_top(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.page_top_value())+ }++ pub(crate) fn width(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.width_value())+ }++ pub(crate) fn height(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.height_value())+ }++ pub(crate) fn scale(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.scale_value())+ }++ pub(crate) fn scroll_by(&self, delta: CssPixelPoint) {+ if delta.x == CssPixels::default() && delta.y == CssPixels::default() {+ return;+ }+ let offset = self.offset.get();+ self.offset+ .set(CssPixelPoint::new(offset.x + delta.x, offset.y + delta.y));+ self.did_scroll();+ self.did_change_offset_or_scale();+ }++ // The compositor zooms and pans the visual viewport too, and hears of every change made to it here.+ fn did_change_offset_or_scale(&self) {+ // SAFETY: The document is live.+ unsafe { web_css_visual_viewport_did_change_offset_or_scale(self.document.as_ptr()) }+ }++ // https://drafts.csswg.org/cssom-view-1/#scrolling-events+ fn did_scroll(&self) {+ // Whenever a visual viewport gets scrolled (whether in response to user interaction or by an API), the user+ // agent must run these steps:++ // 1. Let vv be the VisualViewport object that was scrolled.+ // 2. Let doc be vv's associated document.+ // 3. If (vv, "scroll") is already in doc's pending scroll events, abort these steps.+ // 4. Append (vv, "scroll") to doc's pending scroll events.+ self.append_pending_scroll_event(SCROLL);+ }++ fn transform(&self) -> AffineTransform {+ let offset = self.offset.get();+ let scale = self.scale.get();+ AffineTransform::identity()+ .translated(+ (-offset.x.to_double() * scale) as f32,+ (-offset.y.to_double() * scale) as f32,+ )+ .scaled(scale as f32, scale as f32)+ }++ pub(crate) fn zoom(&self, position: CssPixelPoint, scale_delta: f64) {+ let scale = self.scale.get();+ let new_scale = (scale * (1.0 + scale_delta)).clamp(MIN_ALLOWED_SCALE, MAX_ALLOWED_SCALE);+ let applied_delta = new_scale / scale;++ // For pinch zoom we want focal_point to stay put on screen:+ // scale_new * (focal_point - offset_new) = scale_old * (focal_point - offset_old)+ let old_offset = self.offset.get();+ let new_offset_along = |offset: CssPixels, position: CssPixels, viewport_length: CssPixels| {+ let new_offset = offset.to_double() * scale * applied_delta + position.to_double() * (applied_delta - 1.0);+ let max_offset = (viewport_length.to_double() * (new_scale - 1.0)).max(0.0);+ CssPixels::nearest_value_for(new_offset.clamp(0.0, max_offset) / new_scale)+ };+ let viewport_rect = self.viewport_rect();+ let new_offset = CssPixelPoint::new(+ new_offset_along(old_offset.x, position.x, viewport_rect.width),+ new_offset_along(old_offset.y, position.y, viewport_rect.height),+ );++ self.scale.set(new_scale);+ self.scale_is_new_to_compositor.set(true);+ self.offset.set(new_offset);+ if new_offset != old_offset {+ self.did_scroll();+ }+ self.did_change_offset_or_scale();+ }++ pub(crate) fn set_scale_zoomed_by_compositor(&self, scale: f64) {+ if scale == self.scale.get() {+ return;+ }+ self.scale.set(scale);+ self.did_change_offset_or_scale();+ }++ /// The scale, if this thread changed it since the compositor last heard of it.+ pub(crate) fn take_scale_for_compositor(&self) -> Option<f64> {+ self.scale_is_new_to_compositor.replace(false).then(|| self.scale.get())+ }++ pub(crate) fn map_to_layout_viewport(&self, position: CssPixelPoint) -> CssPixelPoint {+ let inverse = self.transform().inverse().unwrap_or_default();+ let mapped = inverse.map_point(FloatPoint {+ x: position.x.to_int() as f32,+ y: position.y.to_int() as f32,+ });+ CssPixelPoint::new(+ CssPixels::from_integer(mapped.x.round_ties_even() as i64),+ CssPixels::from_integer(mapped.y.round_ties_even() as i64),+ )+ }++ pub(crate) fn map_point_from_layout_viewport(&self, position: CssPixelPoint) -> CssPixelPoint {+ let mapped = self.transform().map_point(FloatPoint {+ x: position.x.to_float(),+ y: position.y.to_float(),+ });+ CssPixelPoint::new(+ CssPixels::nearest_value_for_f32(mapped.x),+ CssPixels::nearest_value_for_f32(mapped.y),+ )+ }++ pub(crate) fn map_rect_from_layout_viewport(&self, rect: CssPixelRect) -> CssPixelRect {+ let mapped = self.transform().map_rect(FloatRect {+ x: rect.x.to_float(),+ y: rect.y.to_float(),+ width: rect.width.to_float(),+ height: rect.height.to_float(),+ });+ CssPixelRect::new(+ CssPixels::nearest_value_for_f32(mapped.x),+ CssPixels::nearest_value_for_f32(mapped.y),+ CssPixels::nearest_value_for_f32(mapped.width),+ CssPixels::nearest_value_for_f32(mapped.height),+ )+ }++ pub(crate) fn reset(&self) {+ self.scale.set(1.0);+ self.scale_is_new_to_compositor.set(true);+ let old_offset = self.offset.replace(CssPixelPoint::default());+ if old_offset != CssPixelPoint::default() {+ self.did_scroll();+ // Resetting performs an instant scroll, so its scrollend event is queued immediately.+ self.append_pending_scroll_event(SCROLLEND);+ }+ self.did_change_offset_or_scale();+ }+}diff --git a/Libraries/LibWeb/CSS/VisualViewport.cpp b/Libraries/LibWeb/CSS/VisualViewport.cppindex 4367b0aa415..c76336f27e9 100644--- a/Libraries/LibWeb/CSS/VisualViewport.cpp+++ b/Libraries/LibWeb/CSS/VisualViewport.cpp@@ -5,14 +5,13 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibGC/Heap.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/VM.h>#include <LibWeb/CSS/VisualViewport.h>#include <LibWeb/DOM/Document.h>-#include <LibWeb/DOM/EventDispatcher.h>-#include <LibWeb/HTML/EventNames.h>+#include <LibWeb/DOM/EventTarget.h>#include <LibWeb/HTML/LocalNavigable.h>#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/Window.h>#include <LibWeb/Layout/RenderDocument.h>#include <LibWeb/Layout/Viewport.h>#include <LibWeb/Painting/BoxViews.h>@@ -20,256 +19,158 @@namespace Web::CSS {-GC_DEFINE_ALLOCATOR(VisualViewport);+namespace {-GC::Ref<VisualViewport> VisualViewport::create(DOM::Document& document)-{- return GC::Heap::the().allocate<VisualViewport>(document);-}--VisualViewport::VisualViewport(DOM::Document& document)- : DOM::EventTarget()- , m_document(document)-{-}--GC::Ptr<Bindings::Wrappable> VisualViewport::relevant_global_impl() const-{- return m_document->window();-}--void VisualViewport::visit_edges(Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_document);-}+struct FFIPixelPoint {+ i32 x;+ i32 y;+};-// https://drafts.csswg.org/cssom-view/#dom-visualviewport-offsetleft-double VisualViewport::offset_left() const-{- // 1. If the visual viewport’s associated document is not fully active, return 0.- if (!m_document->is_fully_active())- return 0;-- // 2. Otherwise, return the offset of the left edge of the visual viewport from the left edge of the layout viewport.- return m_offset.x().to_double();-}+struct FFIPixelRect {+ i32 x;+ i32 y;+ i32 width;+ i32 height;+};-// https://drafts.csswg.org/cssom-view/#dom-visualviewport-offsettop-double VisualViewport::offset_top() const-{- // 1. If the visual viewport’s associated document is not fully active, return 0.- if (!m_document->is_fully_active())- return 0;-- // 2. Otherwise, return the offset of the top edge of the visual viewport from the top edge of the layout viewport.- return m_offset.y().to_double();}-// https://drafts.csswg.org/cssom-view/#dom-visualviewport-pageleft-double VisualViewport::page_left() const+static FFIPixelPoint to_ffi(CSSPixelPoint point){- // 1. If the visual viewport’s associated document is not fully active, return 0.- if (!m_document->is_fully_active())- return 0;-- // 2. Otherwise, return the offset of the left edge of the visual viewport from the- // left edge of the initial containing block of the layout viewport’s document.- return m_document->viewport_rect().x().to_double() + offset_left();+ return { point.x().raw_value(), point.y().raw_value() };}-// https://drafts.csswg.org/cssom-view/#dom-visualviewport-pagetop-double VisualViewport::page_top() const+static CSSPixelPoint from_ffi(FFIPixelPoint point){- // 1. If the visual viewport’s associated document is not fully active, return 0.- if (!m_document->is_fully_active())- return 0;-- // 2. Otherwise, return the offset of the top edge of the visual viewport from the- // top edge of the initial containing block of the layout viewport’s document.- return m_document->viewport_rect().y().to_double() + offset_top();+ return { CSSPixels::from_raw(point.x), CSSPixels::from_raw(point.y) };}-// https://drafts.csswg.org/cssom-view/#dom-visualviewport-width-double VisualViewport::width() const-{- // 1. If the visual viewport’s associated document is not fully active, return 0.- if (!m_document->is_fully_active())- return 0;-- // 2. Otherwise, return the width of the visual viewport- // FIXME: excluding the width of any rendered vertical classic scrollbar that is fixed to the visual viewport.- return m_document->viewport_rect().size().width() / m_scale;-}+extern "C" {-// https://drafts.csswg.org/cssom-view/#dom-visualviewport-height-double VisualViewport::height() const-{- // 1. If the visual viewport’s associated document is not fully active, return 0.- if (!m_document->is_fully_active())- return 0;+// Defined in Bindings/Rust/src/css/exports.rs.+void* web_visual_viewport_create(JSVM*, void* realm, void* document);+void* web_visual_viewport_event_target(void* viewport);+FFIPixelPoint web_visual_viewport_offset(void* viewport);+double web_visual_viewport_offset_left(void* viewport);+double web_visual_viewport_offset_top(void* viewport);+double web_visual_viewport_page_left(void* viewport);+double web_visual_viewport_page_top(void* viewport);+double web_visual_viewport_width(void* viewport);+double web_visual_viewport_height(void* viewport);+double web_visual_viewport_scale(void* viewport);+void web_visual_viewport_scroll_by(void* viewport, FFIPixelPoint delta);+void web_visual_viewport_zoom(void* viewport, FFIPixelPoint position, double scale_delta);+void web_visual_viewport_set_scale_zoomed_by_compositor(void* viewport, double scale);+bool web_visual_viewport_take_scale_for_compositor(void* viewport, double* scale);+FFIPixelPoint web_visual_viewport_map_to_layout_viewport(void* viewport, FFIPixelPoint position);+FFIPixelPoint web_visual_viewport_map_point_from_layout_viewport(void* viewport, FFIPixelPoint position);+FFIPixelRect web_visual_viewport_map_rect_from_layout_viewport(void* viewport, FFIPixelRect rect);+void web_visual_viewport_reset(void* viewport);- // 2. Otherwise, return the height of the visual viewport- // FIXME: excluding the height of any rendered vertical classic scrollbar that is fixed to the visual viewport.- return m_document->viewport_rect().size().height() / m_scale;+// Declared in Bindings/Rust/src/css/visual_viewport.rs.+bool web_css_visual_viewport_document_is_fully_active(void* document);+FFIPixelRect web_css_visual_viewport_document_viewport_rect(void* document);+void web_css_visual_viewport_append_pending_scroll_event(void* document, void* event_target, ReadonlyBytes type);+void web_css_visual_viewport_did_change_offset_or_scale(void* document);}-// https://drafts.csswg.org/cssom-view/#dom-visualviewport-scale-double VisualViewport::scale() const+static void* to_abi(VisualViewport const* viewport){- return m_scale;+ return const_cast<VisualViewport*>(viewport);}-void VisualViewport::set_onresize(WebIDL::CallbackType* event_handler)+static DOM::Document& document_from_abi(void* document){- set_event_handler_attribute(HTML::EventNames::resize, event_handler);+ return *static_cast<DOM::Document*>(static_cast<GC::Cell*>(document));}-WebIDL::CallbackType* VisualViewport::onresize()+bool web_css_visual_viewport_document_is_fully_active(void* document){- return event_handler_attribute(HTML::EventNames::resize);+ return document_from_abi(document).is_fully_active();}-void VisualViewport::set_onscroll(WebIDL::CallbackType* event_handler)+FFIPixelRect web_css_visual_viewport_document_viewport_rect(void* document){- set_event_handler_attribute(HTML::EventNames::scroll, event_handler);+ auto rect = document_from_abi(document).viewport_rect();+ return { rect.x().raw_value(), rect.y().raw_value(), rect.width().raw_value(), rect.height().raw_value() };}-WebIDL::CallbackType* VisualViewport::onscroll()+void web_css_visual_viewport_append_pending_scroll_event(void* document, void* event_target, ReadonlyBytes type){- return event_handler_attribute(HTML::EventNames::scroll);+ auto& target = *static_cast<DOM::EventTarget*>(static_cast<GC::Cell*>(event_target));+ document_from_abi(document).append_pending_scroll_event({ target, Utf16FlyString::from_utf8_without_validation(type) });}-void VisualViewport::set_onscrollend(WebIDL::CallbackType* event_handler)+void web_css_visual_viewport_did_change_offset_or_scale(void* document){- set_event_handler_attribute(HTML::EventNames::scrollend, event_handler);+ VisualViewport::did_change_offset_or_scale(document_from_abi(document));}-WebIDL::CallbackType* VisualViewport::onscrollend()+static void update_accumulated_visual_context(DOM::Document& document){- return event_handler_attribute(HTML::EventNames::scrollend);-}--void VisualViewport::scroll_by(CSSPixelPoint delta)-{- if (delta.is_zero())+ Layout::ForcedReadScope read { document };+ if (document.has_committed_viewport_box() && document.paint_state().has_visual_context_tree(read)) {+ document.paint_state().update_visual_viewport_accumulated_visual_context(read, document);return;- m_offset += delta;- did_scroll();- did_change_offset_or_scale();-}+ }-// The compositor zooms and pans the visual viewport too, and hears of every change made to it here.-void VisualViewport::did_change_offset_or_scale()-{- update_accumulated_visual_context();- m_document->set_needs_repaint(Badge<CSS::VisualViewport> {}, InvalidateDisplayList::No);- if (auto navigable = m_document->navigable())- navigable->did_change_scroll_offset({ .node_id = m_document->unique_id(), .kind = Web::AsyncScrollNodeKind::VisualViewport });+ document.schedule_full_accumulated_visual_context_rebuild(Layout::RustFFI::VisualContextUpdateScope::FreshTree);}-// https://drafts.csswg.org/cssom-view-1/#scrolling-events-void VisualViewport::did_scroll()+void VisualViewport::did_change_offset_or_scale(DOM::Document& document){- // Whenever a visual viewport gets scrolled (whether in response to user interaction or by an API), the user agent- // must run these steps:-- // 1. Let vv be the VisualViewport object that was scrolled.- // 2. Let doc be vv's associated document.- // 3. If (vv, "scroll") is already in doc's pending scroll events, abort these steps.- // 4. Append (vv, "scroll") to doc's pending scroll events.- m_document->append_pending_scroll_event({ *this, HTML::EventNames::scroll });+ update_accumulated_visual_context(document);+ document.set_needs_repaint(Badge<CSS::VisualViewport> {}, InvalidateDisplayList::No);+ if (auto navigable = document.navigable())+ navigable->did_change_scroll_offset({ .node_id = document.unique_id(), .kind = Web::AsyncScrollNodeKind::VisualViewport });}-Gfx::AffineTransform VisualViewport::transform() const+GC::Ref<VisualViewport> VisualViewport::create(DOM::Document& document){- Gfx::AffineTransform transform;- auto offset = m_offset.to_type<double>() * m_scale;- transform.translate(-offset.x(), -offset.y());- transform.scale({ m_scale, m_scale });- return transform;+ auto* viewport = web_visual_viewport_create(JS::HostABI::vm_to_abi(JS::VM::the()), &HTML::relevant_realm(document), static_cast<GC::Cell*>(&document));+ return GC::Ref { *static_cast<VisualViewport*>(viewport) };}-void VisualViewport::zoom(CSSPixelPoint position, double scale_delta)+GC::Ref<DOM::EventTarget> VisualViewport::event_target() const{- static constexpr double MIN_ALLOWED_SCALE = 1.0;- static constexpr double MAX_ALLOWED_SCALE = 5.0;- double new_scale = clamp(m_scale * (1 + scale_delta), MIN_ALLOWED_SCALE, MAX_ALLOWED_SCALE);- double applied_delta = new_scale / m_scale;-- // For pinch zoom we want focal_point to stay put on screen:- // scale_new * (focal_point - offset_new) = scale_old * (focal_point - offset_old)- auto new_offset = m_offset.to_type<double>() * m_scale * applied_delta;- new_offset += position.to_type<double>() * (applied_delta - 1.0f);-- auto viewport_float_size = m_document->navigable()->viewport_rect().size().to_type<double>();- auto max_x_offset = max(0.0, viewport_float_size.width() * (new_scale - 1.0f));- auto max_y_offset = max(0.0, viewport_float_size.height() * (new_scale - 1.0f));- new_offset = { clamp(new_offset.x(), 0.0f, max_x_offset), clamp(new_offset.y(), 0.0f, max_y_offset) };-- m_scale = new_scale;- m_scale_is_new_to_compositor = true;- auto old_offset = m_offset;- m_offset = (new_offset / m_scale).to_type<CSSPixels>();- if (m_offset != old_offset)- did_scroll();- did_change_offset_or_scale();+ return *static_cast<DOM::EventTarget*>(static_cast<GC::Cell*>(web_visual_viewport_event_target(to_abi(this))));}-void VisualViewport::set_scale_zoomed_by_compositor(double scale)-{- if (scale == m_scale)- return;- m_scale = scale;- did_change_offset_or_scale();-}+CSSPixelPoint VisualViewport::offset() const { return from_ffi(web_visual_viewport_offset(to_abi(this))); }+double VisualViewport::offset_left() const { return web_visual_viewport_offset_left(to_abi(this)); }+double VisualViewport::offset_top() const { return web_visual_viewport_offset_top(to_abi(this)); }+double VisualViewport::page_left() const { return web_visual_viewport_page_left(to_abi(this)); }+double VisualViewport::page_top() const { return web_visual_viewport_page_top(to_abi(this)); }+double VisualViewport::width() const { return web_visual_viewport_width(to_abi(this)); }+double VisualViewport::height() const { return web_visual_viewport_height(to_abi(this)); }+double VisualViewport::scale() const { return web_visual_viewport_scale(to_abi(this)); }+void VisualViewport::scroll_by(CSSPixelPoint delta) { web_visual_viewport_scroll_by(this, to_ffi(delta)); }+void VisualViewport::zoom(CSSPixelPoint position, double scale_delta) { web_visual_viewport_zoom(this, to_ffi(position), scale_delta); }+void VisualViewport::set_scale_zoomed_by_compositor(double scale) { web_visual_viewport_set_scale_zoomed_by_compositor(this, scale); }+void VisualViewport::reset() { web_visual_viewport_reset(this); }Optional<double> VisualViewport::take_scale_for_compositor(){- if (!exchange(m_scale_is_new_to_compositor, false))+ double scale = 0;+ if (!web_visual_viewport_take_scale_for_compositor(this, &scale))return {};- return m_scale;+ return scale;}CSSPixelPoint VisualViewport::map_to_layout_viewport(CSSPixelPoint position) const{- auto inverse = transform().inverse().value_or({});- return inverse.map(position.to_type<int>()).to_type<CSSPixels>();+ return from_ffi(web_visual_viewport_map_to_layout_viewport(to_abi(this), to_ffi(position)));}CSSPixelPoint VisualViewport::map_from_layout_viewport(CSSPixelPoint position) const{- return transform().map(position.to_type<float>()).to_type<CSSPixels>();+ return from_ffi(web_visual_viewport_map_point_from_layout_viewport(to_abi(this), to_ffi(position)));}CSSPixelRect VisualViewport::map_from_layout_viewport(CSSPixelRect const& rect) const{- return transform().map(rect.to_type<float>()).to_type<CSSPixels>();-}--void VisualViewport::reset()-{- m_scale = 1.0;- m_scale_is_new_to_compositor = true;- auto old_offset = m_offset;- m_offset = { 0, 0 };- if (m_offset != old_offset) {- did_scroll();- // Resetting performs an instant scroll, so its scrollend event is queued immediately.- m_document->append_pending_scroll_event({ *this, HTML::EventNames::scrollend });- }- did_change_offset_or_scale();-}--void VisualViewport::update_accumulated_visual_context()-{- Layout::ForcedReadScope read { *m_document };- if (m_document->has_committed_viewport_box() && m_document->paint_state().has_visual_context_tree(read)) {- m_document->paint_state().update_visual_viewport_accumulated_visual_context(read, *m_document);- return;- }-- m_document->schedule_full_accumulated_visual_context_rebuild(Layout::RustFFI::VisualContextUpdateScope::FreshTree);+ auto mapped = web_visual_viewport_map_rect_from_layout_viewport(to_abi(this), { rect.x().raw_value(), rect.y().raw_value(), rect.width().raw_value(), rect.height().raw_value() });+ return { CSSPixels::from_raw(mapped.x), CSSPixels::from_raw(mapped.y), CSSPixels::from_raw(mapped.width), CSSPixels::from_raw(mapped.height) };}}diff --git a/Libraries/LibWeb/CSS/VisualViewport.h b/Libraries/LibWeb/CSS/VisualViewport.hindex ebc2efa86fb..d0ffdf4b43b 100644--- a/Libraries/LibWeb/CSS/VisualViewport.h+++ b/Libraries/LibWeb/CSS/VisualViewport.h@@ -7,27 +7,28 @@#pragma once-#include <LibGfx/AffineTransform.h>-#include <LibWeb/DOM/EventTarget.h>+#include <LibGC/Ptr.h>+#include <LibWeb/Bindings/RustInterface.h>+#include <LibWeb/Bindings/VisualViewport.h>#include <LibWeb/Export.h>+#include <LibWeb/Forward.h>#include <LibWebCommon/PixelUnits.h>namespace Web::CSS {// https://drafts.csswg.org/cssom-view/#visualviewport-class WEB_API VisualViewport final : public DOM::EventTarget {- WEB_WRAPPABLE(VisualViewport, DOM::EventTarget);- GC_DECLARE_ALLOCATOR(VisualViewport);+class WEB_API VisualViewport final : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(VisualViewport, visual_viewport)public:[[nodiscard]] static GC::Ref<VisualViewport> create(DOM::Document&);- virtual ~VisualViewport() override = default;+ // The compositor zooms and pans the visual viewport too, and hears of every change made to it here.+ static void did_change_offset_or_scale(DOM::Document&);- DOM::Document& document() { return m_document; }- DOM::Document const& document() const { return m_document; }+ [[nodiscard]] GC::Ref<DOM::EventTarget> event_target() const;- CSSPixelPoint offset() const { return m_offset; }+ CSSPixelPoint offset() const;[[nodiscard]] double offset_left() const;[[nodiscard]] double offset_top() const;@@ -40,16 +41,8 @@ public:[[nodiscard]] double scale() const;- void set_onresize(WebIDL::CallbackType*);- WebIDL::CallbackType* onresize();- void set_onscroll(WebIDL::CallbackType*);- WebIDL::CallbackType* onscroll();- void set_onscrollend(WebIDL::CallbackType*);- WebIDL::CallbackType* onscrollend();-void scroll_by(CSSPixelPoint delta);- [[nodiscard]] Gfx::AffineTransform transform() const;void zoom(CSSPixelPoint position, double scale_delta);void set_scale_zoomed_by_compositor(double scale);// The scale, if this thread changed it since the compositor last heard of it.@@ -58,20 +51,6 @@ public:CSSPixelPoint map_from_layout_viewport(CSSPixelPoint) const;CSSPixelRect map_from_layout_viewport(CSSPixelRect const&) const;void reset();--private:- explicit VisualViewport(DOM::Document&);- virtual void visit_edges(Cell::Visitor&) override;- virtual GC::Ptr<Bindings::Wrappable> relevant_global_impl() const override;-- void did_scroll();- void did_change_offset_or_scale();- void update_accumulated_visual_context();-- GC::Ref<DOM::Document> m_document;- CSSPixelPoint m_offset;- double m_scale { 1.0 };- bool m_scale_is_new_to_compositor { false };};}diff --git a/Libraries/LibWeb/CSS/VisualViewport.idl b/Libraries/LibWeb/CSS/VisualViewport.idlindex 3ded62c33b4..ab3ffce38fc 100644--- a/Libraries/LibWeb/CSS/VisualViewport.idl+++ b/Libraries/LibWeb/CSS/VisualViewport.idl@@ -1,5 +1,5 @@// https://drafts.csswg.org/cssom-view/#the-visualviewport-interface-[Exposed=Window]+[Exposed=Window, ImplementedIn=Rust]interface VisualViewport : EventTarget {readonly attribute double offsetLeft;diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cppindex d0e66b35649..4a0e4038d57 100644--- a/Libraries/LibWeb/DOM/Document.cpp+++ b/Libraries/LibWeb/DOM/Document.cpp@@ -5732,7 +5732,7 @@ void Document::run_the_resize_steps()UIEvents::EventNames::resize,HighResolutionTime::current_high_resolution_time(relevant_global_object(*this)));visual_viewport_resize_event->set_is_trusted(true);- visual_viewport.dispatch_event(visual_viewport_resize_event);+ visual_viewport.event_target()->dispatch_event(visual_viewport_resize_event);}}}diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cppindex 4b128c9ec81..46527611d8c 100644--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp@@ -5225,7 +5225,7 @@ static GC::Ptr<DOM::EventTarget> scroll_event_target_for_async_scroll_node(DOM::if (stable_node_id.kind == Web::AsyncScrollNodeKind::VisualViewport) {if (stable_node_id.node_id != document.unique_id())return {};- return document.visual_viewport();+ return document.visual_viewport()->event_target();}return element_for_async_scroll_node_stable_id(document, stable_node_id);}@@ -5703,7 +5703,7 @@ void LocalNavigable::end_completed_scroll_sequences()if (auto* element = as_if<DOM::Element>(*target))target_is_in_document = &element->document() == document.ptr() && element->is_connected();else- target_is_in_document = target.ptr() == document.ptr() || target.ptr() == document->visual_viewport().ptr();+ target_is_in_document = target.ptr() == document.ptr() || target.ptr() == document->visual_viewport()->event_target().ptr();if (!target_is_in_document) {m_scroll_sequences.remove(index);continue;