Truly independent web browser
LibWeb: Draw SVG images that hold foreign content from a raster
Aliaksandr Kalenik60927dd9051d
diff --git a/Libraries/LibWeb/Compositor/CompositorConnection.cpp b/Libraries/LibWeb/Compositor/CompositorConnection.cppindex f4b86d0ea70..4c0febd54e6 100644--- a/Libraries/LibWeb/Compositor/CompositorConnection.cpp+++ b/Libraries/LibWeb/Compositor/CompositorConnection.cpp@@ -386,6 +386,24 @@ bool CompositorConnection::rasterize_image(Layout::RustFFI::FfiImageRasterizatioauto 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);+}++bool CompositorConnection::rasterize_last_recording(Layout::RustFFI::DocumentHost const& document_host, Layout::BegunRead const& read, NonnullRefPtr<Gfx::Bitmap> target)+{+ if (!can_send_message_to_compositor())+ return false;++ // 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);+}++bool CompositorConnection::wait_for_rasterization(u64 token)+{while (true) {auto answer = wait_for_specific_endpoint_message<Messages::CompositorWebContentClient::DidRasterizeDisplayList>();if (!answer) {@@ -399,7 +417,7 @@ bool CompositorConnection::rasterize_image(Layout::RustFFI::FfiImageRasterizatiovoid CompositorConnection::did_rasterize_display_list(u64, bool){- // CompositorConnection::rasterize_image() waits for its answer, and an answer it gave up on goes nowhere.+ // CompositorConnection::wait_for_rasterization() waits for its answer, and an answer it gave up on goes nowhere.}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 08623eedb0c..8f40a863a67 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;}@@ -80,6 +81,9 @@ public:Web::Compositor::PlaceholderCanvasPixels get_placeholder_canvas_pixels(Compositing::CanvasId, Gfx::IntRect);// Has the compositor rasterize `image` into `target`, and waits for it to.bool rasterize_image(Layout::RustFFI::FfiImageRasterization const&, NonnullRefPtr<Gfx::Bitmap> target);+ // Has the compositor rasterize the recording the document of the host took in last into `target`, and waits for+ // it to.+ bool rasterize_last_recording(Layout::RustFFI::DocumentHost const&, Layout::BegunRead const&, NonnullRefPtr<Gfx::Bitmap> target);void invalidate_wheel_event_listener_state(Web::CompositorContextId, u64 generation);void invalidate_keyboard_scroll_state(Web::CompositorContextId, u64 generation);Compositing::WheelEventAnswer take_wheel_event_from_main_thread(Web::CompositorContextId, Web::MouseEvent const&, Compositing::AsyncScrollOperationTracking, Compositing::WheelEventRouting);@@ -140,6 +144,7 @@ private: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);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/Compositor/CompositorHost.cpp b/Libraries/LibWeb/Compositor/CompositorHost.cppindex 19581170f6b..16287770d2d 100644--- a/Libraries/LibWeb/Compositor/CompositorHost.cpp+++ b/Libraries/LibWeb/Compositor/CompositorHost.cpp@@ -408,6 +408,14 @@ bool CompositorHost::rasterize_image(Layout::RustFFI::FfiImageRasterization consreturn connection->rasterize_image(image, move(target));}+bool CompositorHost::rasterize_last_recording(Layout::RustFFI::DocumentHost const& document_host, Layout::BegunRead const& read, NonnullRefPtr<Gfx::Bitmap> target) const+{+ auto* connection = compositor_connection();+ if (!connection)+ return false;+ return connection->rasterize_last_recording(document_host, read, move(target));+}+void CompositorHost::destroy_context(Web::CompositorContextId context_id){if (auto* connection = compositor_connection()) {diff --git a/Libraries/LibWeb/Compositor/CompositorHost.h b/Libraries/LibWeb/Compositor/CompositorHost.hindex 62ac3f93b01..da3fd3033d5 100644--- a/Libraries/LibWeb/Compositor/CompositorHost.h+++ b/Libraries/LibWeb/Compositor/CompositorHost.h@@ -31,6 +31,7 @@namespace Web::Layout::RustFFI {+struct DocumentHost;struct FfiImageRasterization;}@@ -143,6 +144,9 @@ public:// Has the compositor draw an image into the target, which must be a shareable BGRA8888 bitmap with premultiplied// alpha. Returns false if nothing was drawn.bool rasterize_image(Layout::RustFFI::FfiImageRasterization const&, NonnullRefPtr<Gfx::Bitmap> target) const;+ // Has the compositor draw the recording the document of the host took in last into the target, a bitmap as+ // rasterize_image() takes, the size of the document's viewport. Returns false if nothing was drawn.+ bool rasterize_last_recording(Layout::RustFFI::DocumentHost const&, Layout::BegunRead const&, NonnullRefPtr<Gfx::Bitmap> target) const;void destroy_context(Web::CompositorContextId);void set_parent_context(Web::CompositorContextId, Optional<Web::CompositorContextId>);diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.hindex 0dafdc81dc0..ae5037b2ce3 100644--- a/Libraries/LibWeb/DOM/Document.h+++ b/Libraries/LibWeb/DOM/Document.h@@ -769,6 +769,11 @@ public:Optional<CSS::PreferredColorScheme> svg_image_color_scheme() const { return m_svg_image_color_scheme; }void set_svg_image_color_scheme(CSS::PreferredColorScheme color_scheme) { m_svg_image_color_scheme = color_scheme; }+ // Whether this document of an SVG image holds content that is not SVG, which only paints in full through the+ // document's visual contexts. Such an image is drawn from a raster of the document.+ bool decoded_svg_holds_foreign_content() const { return m_decoded_svg_holds_foreign_content; }+ void set_decoded_svg_holds_foreign_content(bool holds_foreign_content) { m_decoded_svg_holds_foreign_content = holds_foreign_content; }+bool needs_mathml_and_svg_user_agent_style_sheets() const { return m_needs_mathml_and_svg_user_agent_style_sheets; }void set_needs_mathml_and_svg_user_agent_style_sheets();@@ -2055,6 +2060,7 @@ private:// of those namespaces, so they are attached the first time one arrives. Once attached they stay:// a document that held one is likely to again, and every element pays for the flip.Optional<CSS::PreferredColorScheme> m_svg_image_color_scheme;+ bool m_decoded_svg_holds_foreign_content { false };bool m_needs_mathml_and_svg_user_agent_style_sheets { false };bool m_has_element_with_auto_directionality { false };diff --git a/Libraries/LibWeb/Rust/src/painting/display_list_resources.rs b/Libraries/LibWeb/Rust/src/painting/display_list_resources.rsindex 2afaa402505..a2fc0e14e66 100644--- a/Libraries/LibWeb/Rust/src/painting/display_list_resources.rs+++ b/Libraries/LibWeb/Rust/src/painting/display_list_resources.rs@@ -8,9 +8,12 @@//! for as long as anything holds the list. The compositor is sent the ones it lacks ahead of the list.use crate::painting::display_list::builder::RecordedDisplayList;+use crate::painting::display_list::commands::ImageFrameResourceId;use crate::painting::display_list::ids::allocate_display_list_id;+use crate::painting::display_list::recorder::DisplayListRecorder;use crate::painting::display_list::storage::DisplayListStorage;use crate::painting::display_list::summary::{DisplayListSummary, summarize};+use crate::painting::force_dark::ForceDarkRole;use crate::painting::visual_context::VisualContextTree;use libcompositing_rust::ipc_types::{Compositing_DisplayListProperties, NestedDisplayListResource};use libgfx_rust::font::FontHandle;@@ -127,6 +130,28 @@ impl NestedDisplayList {Self::new(storage, visual_context_tree, root_group_color, resources)}+ /// A list that draws `frame`, the raster of an SVG image of `size`, under a new id.+ pub(crate) fn drawing_image_frame(frame: ImageFrameHandle, size: libgfx_rust::IntSize) -> Arc<Self> {+ let mut recorder = DisplayListRecorder::new(None);+ recorder.draw_scaled_decoded_image_frame(+ libgfx_rust::FloatRect::new(0.0, 0.0, size.width as f32, size.height as f32),+ None,+ ImageFrameResourceId(frame.id()),+ libgfx_rust::ScalingMode::Bilinear,+ libgfx_rust::CompositingAndBlendingOperator::Normal,+ None,+ ForceDarkRole::None,+ );+ let mut resources = DisplayListResources::default();+ resources.image_frames.insert(frame.id(), frame);+ Self::recorded(+ Arc::new(recorder.into_builder().finish()),+ Arc::new(VisualContextTree::create_identity()),+ libgfx_rust::Color::TRANSPARENT,+ resources,+ )+ }+/// An empty list, which stands in for an SVG image that has nothing to show.pub(crate) fn empty() -> Arc<Self> {let storage = DisplayListStorage::empty();diff --git a/Libraries/LibWeb/Rust/src/painting/rasterize.rs b/Libraries/LibWeb/Rust/src/painting/rasterize.rsindex bf6a65854ff..0344af3e181 100644--- a/Libraries/LibWeb/Rust/src/painting/rasterize.rs+++ b/Libraries/LibWeb/Rust/src/painting/rasterize.rs@@ -126,13 +126,16 @@ 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`.-/// Answers whether the compositor could still be reached.+/// 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(poster: &CompositorPoster,token: u64,- display_list: RecordedDisplayList,- resources: DisplayListResources,+ display_list: Arc<RecordedDisplayList>,+ tree: Arc<VisualContextTree>,+ root_group_color: libgfx_rust::Color,+ resources: &DisplayListResources,target_bitmap: *const c_void,) -> bool {let resources = resources.with_nested_resources();@@ -142,13 +145,12 @@ fn post_rasterization(if !unsafe { poster.stage_rasterization(token, &fonts, &image_frames, target_bitmap) } {return false;}- let tree = Arc::new(VisualContextTree::create_identity());- let storage = DisplayListStorage::recorded(Arc::new(display_list), tree.clone());+ let storage = DisplayListStorage::recorded(display_list, tree.clone());let properties = Compositing_DisplayListProperties {id: allocate_display_list_id(),compatible_visual_context_tree_structural_epoch: tree.structural_epoch,surface_clear_color: None,- root_group_color: libgfx_rust::Color::TRANSPARENT,+ root_group_color,};let Some(display_list) = poster.share_display_list(&storage, properties, None) else {eprintln!(@@ -190,5 +192,51 @@ pub unsafe extern "C" fn render_state_rasterize_image(let poster = unsafe { CompositorPoster::adopt(poster) };// SAFETY: As above.let (display_list, resources) = unsafe { record_image(image) };- post_rasterization(&poster, token, display_list, resources, target_bitmap)+ post_rasterization(+ &poster,+ token,+ Arc::new(display_list),+ Arc::new(VisualContextTree::create_identity()),+ libgfx_rust::Color::TRANSPARENT,+ &resources,+ target_bitmap,+ )+}++/// 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.+///+/// # 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.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn render_state_rasterize_last_recording(+ poster: FfiThreadSafeMessagePoster,+ token: u64,+ host: &DocumentHost,+ read: &crate::render_state::BegunRead,+ target_bitmap: *const c_void,+) -> bool {+ // SAFETY: Guaranteed by the caller.+ let poster = unsafe { 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;+ };+ post_rasterization(+ &poster,+ token,+ recording.display_list.clone(),+ tree,+ recording.root_group_color,+ &recording.resources,+ target_bitmap,+ )}diff --git a/Libraries/LibWeb/Rust/src/painting/vector_image_cache.rs b/Libraries/LibWeb/Rust/src/painting/vector_image_cache.rsindex 58396658d13..4bc83c67186 100644--- a/Libraries/LibWeb/Rust/src/painting/vector_image_cache.rs+++ b/Libraries/LibWeb/Rust/src/painting/vector_image_cache.rs@@ -133,6 +133,27 @@ pub unsafe extern "C" fn render_state_keep_last_recording_as_vector_image();}+/// Has the SVG image document of `host` keep a display list that draws `image_frame`, a `Gfx::DecodedImageFrame` of+/// `size` that the document was rasterized into, as its rendering for `key`.+///+/// # Safety+///+/// `host` must be a live document host, on its document's thread, and `image_frame` must be live for the call.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn render_state_keep_image_frame_as_vector_image(+ host: &DocumentHost,+ key: &FfiVectorImageKey,+ image_frame: *const std::ffi::c_void,+ size: libgfx_rust::IntSize,+) {+ // SAFETY: The caller keeps the frame live for the call.+ let frame = unsafe { libgfx_rust::image_frame::ImageFrameHandle::retain(image_frame) };+ host.vector_images().keep(+ VectorImageKey::of(key),+ NestedDisplayList::drawing_image_frame(frame, size),+ );+}+/// Has the SVG image document of `host` forget its renderings: what it shows changed.#[unsafe(no_mangle)]pub extern "C" fn render_state_forget_vector_images(host: &DocumentHost) {diff --git a/Libraries/LibWeb/SVG/SVGDecodedImageData.cpp b/Libraries/LibWeb/SVG/SVGDecodedImageData.cppindex 1374bdc7054..e44daae5817 100644--- a/Libraries/LibWeb/SVG/SVGDecodedImageData.cpp+++ b/Libraries/LibWeb/SVG/SVGDecodedImageData.cpp@@ -27,6 +27,7 @@#include <LibWeb/Painting/PaintingRustBridge.h>#include <LibWeb/Platform/EventLoopPlugin.h>#include <LibWeb/SVG/SVGDecodedImageData.h>+#include <LibWeb/SVG/SVGForeignObjectElement.h>#include <LibWeb/SVG/SVGSVGElement.h>#include <LibWeb/XML/XMLDocumentBuilder.h>#include <LibXML/Parser/Parser.h>@@ -192,6 +193,12 @@ SVGDecodedImageData::SVGDecodedImageData(GC::Ref<Page> page, GC::Ref<SVGPageClie, m_root_element(root_element), m_vector_content_identity(next_vector_content_identity()){+ bool holds_foreign_content = false;+ document->for_each_in_subtree_of_type<SVGForeignObjectElement>([&](auto&) {+ holds_foreign_content = true;+ return TraversalDecision::Break;+ });+ document->set_decoded_svg_holds_foreign_content(holds_foreign_content);}u64 SVGDecodedImageData::next_vector_content_identity()@@ -270,7 +277,29 @@ Layout::RustFFI::DocumentHost const* SVGDecodedImageData::render_at_scale(PaintiVERIFY(m_document->has_committed_viewport_box());auto* host = m_document->layout_node_arena().host();- Layout::RustFFI::render_state_keep_last_recording_as_vector_image(host, read, &ffi_key);+ if (!m_document->decoded_svg_holds_foreign_content()) {+ Layout::RustFFI::render_state_keep_last_recording_as_vector_image(host, read, &ffi_key);+ return host;+ }++ // Foreign content paints in full only through the document's visual contexts, so a page that draws the image+ // draws a raster of the document.+ auto* compositor_host = host_compositor();+ if (!compositor_host)+ return nullptr;+ Gfx::IntSize raster_size {+ max(1, static_cast<int>(lroundf(key.css_size.width().to_float() * key.raster_scale))),+ max(1, static_cast<int>(lroundf(key.css_size.height().to_float() * key.raster_scale))),+ };+ auto bitmap = Gfx::Bitmap::create_shareable(Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, raster_size);+ if (bitmap.is_error())+ return nullptr;+ if (!compositor_host->rasterize_last_recording(*host, read, bitmap.value()))+ return nullptr;+ auto frame = Gfx::DecodedImageFrame::create(*bitmap.value());+ if (frame.is_error())+ return nullptr;+ Layout::RustFFI::render_state_keep_image_frame_as_vector_image(host, &ffi_key, &frame.value(), raster_size);return host;}