SVGDecodedImageData.cpp 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. /*
  2. * Copyright (c) 2023, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibGfx/Bitmap.h>
  7. #include <LibWeb/DOM/Document.h>
  8. #include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
  9. #include <LibWeb/HTML/BrowsingContext.h>
  10. #include <LibWeb/HTML/DocumentState.h>
  11. #include <LibWeb/HTML/NavigationParams.h>
  12. #include <LibWeb/HTML/Parser/HTMLParser.h>
  13. #include <LibWeb/HTML/TraversableNavigable.h>
  14. #include <LibWeb/Layout/Viewport.h>
  15. #include <LibWeb/Page/Page.h>
  16. #include <LibWeb/Painting/PaintContext.h>
  17. #include <LibWeb/Painting/PaintingCommandExecutorCPU.h>
  18. #include <LibWeb/Painting/ViewportPaintable.h>
  19. #include <LibWeb/SVG/SVGDecodedImageData.h>
  20. #include <LibWeb/SVG/SVGSVGElement.h>
  21. namespace Web::SVG {
  22. class SVGDecodedImageData::SVGPageClient final : public PageClient {
  23. public:
  24. explicit SVGPageClient(Page& host_page)
  25. : m_host_page(host_page)
  26. {
  27. }
  28. virtual ~SVGPageClient() override = default;
  29. Page& m_host_page;
  30. Page* m_svg_page { nullptr };
  31. virtual Page& page() override { return *m_svg_page; }
  32. virtual Page const& page() const override { return *m_svg_page; }
  33. virtual bool is_connection_open() const override { return false; }
  34. virtual Gfx::Palette palette() const override { return m_host_page.client().palette(); }
  35. virtual DevicePixelRect screen_rect() const override { return {}; }
  36. virtual double device_pixels_per_css_pixel() const override { return 1.0; }
  37. virtual CSS::PreferredColorScheme preferred_color_scheme() const override { return m_host_page.client().preferred_color_scheme(); }
  38. virtual void request_file(FileRequest) override { }
  39. virtual void paint(DevicePixelRect const&, Gfx::Bitmap&) override { }
  40. };
  41. ErrorOr<NonnullRefPtr<SVGDecodedImageData>> SVGDecodedImageData::create(Page& host_page, AK::URL const& url, ByteBuffer data)
  42. {
  43. auto page_client = make<SVGPageClient>(host_page);
  44. auto page = make<Page>(*page_client);
  45. page_client->m_svg_page = page.ptr();
  46. page->set_top_level_traversable(MUST(Web::HTML::TraversableNavigable::create_a_fresh_top_level_traversable(*page, AK::URL("about:blank"))));
  47. JS::NonnullGCPtr<HTML::Navigable> navigable = page->top_level_traversable();
  48. auto response = Fetch::Infrastructure::Response::create(navigable->vm());
  49. response->url_list().append(url);
  50. HTML::NavigationParams navigation_params {
  51. .id = {},
  52. .navigable = navigable,
  53. .request = nullptr,
  54. .response = response,
  55. .fetch_controller = nullptr,
  56. .commit_early_hints = nullptr,
  57. .coop_enforcement_result = HTML::CrossOriginOpenerPolicyEnforcementResult {},
  58. .reserved_environment = {},
  59. .origin = HTML::Origin {},
  60. .policy_container = HTML::PolicyContainer {},
  61. .final_sandboxing_flag_set = HTML::SandboxingFlagSet {},
  62. .cross_origin_opener_policy = HTML::CrossOriginOpenerPolicy {},
  63. .about_base_url = {},
  64. };
  65. // FIXME: Use Navigable::navigate() instead of manually replacing the navigable's document.
  66. auto document = DOM::Document::create_and_initialize(DOM::Document::Type::HTML, "text/html"_string, navigation_params).release_value_but_fixme_should_propagate_errors();
  67. navigable->set_ongoing_navigation({});
  68. navigable->active_document()->destroy();
  69. navigable->active_session_history_entry()->document_state->set_document(document);
  70. auto parser = HTML::HTMLParser::create_with_uncertain_encoding(document, data);
  71. parser->run(document->url());
  72. // Perform some DOM surgery to make the SVG root element be the first child of the Document.
  73. // FIXME: This is a huge hack until we figure out how to actually parse separate SVG files.
  74. auto* svg_root = document->body()->first_child_of_type<SVG::SVGSVGElement>();
  75. if (!svg_root)
  76. return Error::from_string_literal("SVGDecodedImageData: Invalid SVG input");
  77. svg_root->remove();
  78. document->remove_all_children();
  79. MUST(document->append_child(*svg_root));
  80. return adopt_nonnull_ref_or_enomem(new (nothrow) SVGDecodedImageData(move(page), move(page_client), move(document), move(svg_root)));
  81. }
  82. SVGDecodedImageData::SVGDecodedImageData(NonnullOwnPtr<Page> page, NonnullOwnPtr<SVGPageClient> page_client, JS::Handle<DOM::Document> document, JS::Handle<SVG::SVGSVGElement> root_element)
  83. : m_page(move(page))
  84. , m_page_client(move(page_client))
  85. , m_document(move(document))
  86. , m_root_element(move(root_element))
  87. {
  88. }
  89. SVGDecodedImageData::~SVGDecodedImageData() = default;
  90. RefPtr<Gfx::Bitmap> SVGDecodedImageData::render(Gfx::IntSize size) const
  91. {
  92. auto bitmap = Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, size).release_value_but_fixme_should_propagate_errors();
  93. VERIFY(m_document->navigable());
  94. m_document->navigable()->set_viewport_rect({ 0, 0, size.width(), size.height() });
  95. m_document->update_layout();
  96. Painting::RecordingPainter recording_painter;
  97. PaintContext context(recording_painter, m_page_client->palette(), m_page_client->device_pixels_per_css_pixel());
  98. m_document->paintable()->paint_all_phases(context);
  99. Painting::PaintingCommandExecutorCPU executor { *bitmap };
  100. recording_painter.execute(executor);
  101. return bitmap;
  102. }
  103. RefPtr<Gfx::ImmutableBitmap> SVGDecodedImageData::bitmap(size_t, Gfx::IntSize size) const
  104. {
  105. if (size.is_empty())
  106. return nullptr;
  107. if (m_immutable_bitmap && m_immutable_bitmap->size() == size)
  108. return m_immutable_bitmap;
  109. m_immutable_bitmap = Gfx::ImmutableBitmap::create(*render(size));
  110. return m_immutable_bitmap;
  111. }
  112. Optional<CSSPixels> SVGDecodedImageData::intrinsic_width() const
  113. {
  114. // https://www.w3.org/TR/SVG2/coords.html#SizingSVGInCSS
  115. m_document->update_style();
  116. auto const* root_element_style = m_root_element->computed_css_values();
  117. VERIFY(root_element_style);
  118. auto const& width_value = root_element_style->size_value(CSS::PropertyID::Width);
  119. if (width_value.is_length() && width_value.length().is_absolute())
  120. return width_value.length().absolute_length_to_px();
  121. return {};
  122. }
  123. Optional<CSSPixels> SVGDecodedImageData::intrinsic_height() const
  124. {
  125. // https://www.w3.org/TR/SVG2/coords.html#SizingSVGInCSS
  126. m_document->update_style();
  127. auto const* root_element_style = m_root_element->computed_css_values();
  128. VERIFY(root_element_style);
  129. auto const& height_value = root_element_style->size_value(CSS::PropertyID::Height);
  130. if (height_value.is_length() && height_value.length().is_absolute())
  131. return height_value.length().absolute_length_to_px();
  132. return {};
  133. }
  134. Optional<CSSPixelFraction> SVGDecodedImageData::intrinsic_aspect_ratio() const
  135. {
  136. // https://www.w3.org/TR/SVG2/coords.html#SizingSVGInCSS
  137. auto width = intrinsic_width();
  138. auto height = intrinsic_height();
  139. if (width.has_value() && height.has_value())
  140. return *width / *height;
  141. if (auto const& viewbox = m_root_element->view_box(); viewbox.has_value())
  142. return CSSPixels::nearest_value_for(viewbox->width) / CSSPixels::nearest_value_for(viewbox->height);
  143. return {};
  144. }
  145. }