SVGFormattingContext.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. /*
  2. * Copyright (c) 2021-2023, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, Sam Atkins <atkinssj@serenityos.org>
  4. * Copyright (c) 2022, Tobias Christiansen <tobyase@serenityos.org>
  5. * Copyright (c) 2023, MacDue <macdue@dueutil.tech>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/Debug.h>
  10. #include <LibGfx/BoundingBox.h>
  11. #include <LibWeb/Layout/BlockFormattingContext.h>
  12. #include <LibWeb/Layout/SVGFormattingContext.h>
  13. #include <LibWeb/Layout/SVGGeometryBox.h>
  14. #include <LibWeb/Layout/SVGSVGBox.h>
  15. #include <LibWeb/Layout/SVGTextBox.h>
  16. #include <LibWeb/SVG/SVGForeignObjectElement.h>
  17. #include <LibWeb/SVG/SVGGElement.h>
  18. #include <LibWeb/SVG/SVGMaskElement.h>
  19. #include <LibWeb/SVG/SVGSVGElement.h>
  20. #include <LibWeb/SVG/SVGSymbolElement.h>
  21. #include <LibWeb/SVG/SVGUseElement.h>
  22. namespace Web::Layout {
  23. SVGFormattingContext::SVGFormattingContext(LayoutState& state, Box const& box, FormattingContext* parent)
  24. : FormattingContext(Type::SVG, state, box, parent)
  25. {
  26. }
  27. SVGFormattingContext::~SVGFormattingContext() = default;
  28. CSSPixels SVGFormattingContext::automatic_content_width() const
  29. {
  30. return 0;
  31. }
  32. CSSPixels SVGFormattingContext::automatic_content_height() const
  33. {
  34. return 0;
  35. }
  36. struct ViewBoxTransform {
  37. CSSPixelPoint offset;
  38. double scale_factor;
  39. };
  40. // https://svgwg.org/svg2-draft/coords.html#PreserveAspectRatioAttribute
  41. static ViewBoxTransform scale_and_align_viewbox_content(SVG::PreserveAspectRatio const& preserve_aspect_ratio,
  42. SVG::ViewBox const& view_box, Gfx::FloatSize viewbox_scale, auto const& svg_box_state)
  43. {
  44. ViewBoxTransform viewbox_transform {};
  45. switch (preserve_aspect_ratio.meet_or_slice) {
  46. case SVG::PreserveAspectRatio::MeetOrSlice::Meet:
  47. // meet (the default) - Scale the graphic such that:
  48. // - aspect ratio is preserved
  49. // - the entire ‘viewBox’ is visible within the SVG viewport
  50. // - the ‘viewBox’ is scaled up as much as possible, while still meeting the other criteria
  51. viewbox_transform.scale_factor = min(viewbox_scale.width(), viewbox_scale.height());
  52. break;
  53. case SVG::PreserveAspectRatio::MeetOrSlice::Slice:
  54. // slice - Scale the graphic such that:
  55. // aspect ratio is preserved
  56. // the entire SVG viewport is covered by the ‘viewBox’
  57. // the ‘viewBox’ is scaled down as much as possible, while still meeting the other criteria
  58. viewbox_transform.scale_factor = max(viewbox_scale.width(), viewbox_scale.height());
  59. break;
  60. default:
  61. VERIFY_NOT_REACHED();
  62. }
  63. // Handle X alignment:
  64. if (svg_box_state.has_definite_width()) {
  65. switch (preserve_aspect_ratio.align) {
  66. case SVG::PreserveAspectRatio::Align::xMinYMin:
  67. case SVG::PreserveAspectRatio::Align::xMinYMid:
  68. case SVG::PreserveAspectRatio::Align::xMinYMax:
  69. // Align the <min-x> of the element's ‘viewBox’ with the smallest X value of the SVG viewport.
  70. viewbox_transform.offset.translate_by(0, 0);
  71. break;
  72. case SVG::PreserveAspectRatio::Align::None: {
  73. // Do not force uniform scaling. Scale the graphic content of the given element non-uniformly
  74. // if necessary such that the element's bounding box exactly matches the SVG viewport rectangle.
  75. // FIXME: None is unimplemented (treat as xMidYMid)
  76. [[fallthrough]];
  77. }
  78. case SVG::PreserveAspectRatio::Align::xMidYMin:
  79. case SVG::PreserveAspectRatio::Align::xMidYMid:
  80. case SVG::PreserveAspectRatio::Align::xMidYMax:
  81. // Align the midpoint X value of the element's ‘viewBox’ with the midpoint X value of the SVG viewport.
  82. viewbox_transform.offset.translate_by((svg_box_state.content_width() - CSSPixels::nearest_value_for(view_box.width * viewbox_transform.scale_factor)) / 2, 0);
  83. break;
  84. case SVG::PreserveAspectRatio::Align::xMaxYMin:
  85. case SVG::PreserveAspectRatio::Align::xMaxYMid:
  86. case SVG::PreserveAspectRatio::Align::xMaxYMax:
  87. // Align the <min-x>+<width> of the element's ‘viewBox’ with the maximum X value of the SVG viewport.
  88. viewbox_transform.offset.translate_by((svg_box_state.content_width() - CSSPixels::nearest_value_for(view_box.width * viewbox_transform.scale_factor)), 0);
  89. break;
  90. default:
  91. VERIFY_NOT_REACHED();
  92. }
  93. }
  94. if (svg_box_state.has_definite_width()) {
  95. switch (preserve_aspect_ratio.align) {
  96. case SVG::PreserveAspectRatio::Align::xMinYMin:
  97. case SVG::PreserveAspectRatio::Align::xMidYMin:
  98. case SVG::PreserveAspectRatio::Align::xMaxYMin:
  99. // Align the <min-y> of the element's ‘viewBox’ with the smallest Y value of the SVG viewport.
  100. viewbox_transform.offset.translate_by(0, 0);
  101. break;
  102. case SVG::PreserveAspectRatio::Align::None: {
  103. // Do not force uniform scaling. Scale the graphic content of the given element non-uniformly
  104. // if necessary such that the element's bounding box exactly matches the SVG viewport rectangle.
  105. // FIXME: None is unimplemented (treat as xMidYMid)
  106. [[fallthrough]];
  107. }
  108. case SVG::PreserveAspectRatio::Align::xMinYMid:
  109. case SVG::PreserveAspectRatio::Align::xMidYMid:
  110. case SVG::PreserveAspectRatio::Align::xMaxYMid:
  111. // Align the midpoint Y value of the element's ‘viewBox’ with the midpoint Y value of the SVG viewport.
  112. viewbox_transform.offset.translate_by(0, (svg_box_state.content_height() - CSSPixels::nearest_value_for(view_box.height * viewbox_transform.scale_factor)) / 2);
  113. break;
  114. case SVG::PreserveAspectRatio::Align::xMinYMax:
  115. case SVG::PreserveAspectRatio::Align::xMidYMax:
  116. case SVG::PreserveAspectRatio::Align::xMaxYMax:
  117. // Align the <min-y>+<height> of the element's ‘viewBox’ with the maximum Y value of the SVG viewport.
  118. viewbox_transform.offset.translate_by(0, (svg_box_state.content_height() - CSSPixels::nearest_value_for(view_box.height * viewbox_transform.scale_factor)));
  119. break;
  120. default:
  121. VERIFY_NOT_REACHED();
  122. }
  123. }
  124. return viewbox_transform;
  125. }
  126. static bool is_container_element(Node const& node)
  127. {
  128. // https://svgwg.org/svg2-draft/struct.html#GroupsOverview
  129. auto* dom_node = node.dom_node();
  130. if (!dom_node)
  131. return false;
  132. if (is<SVG::SVGUseElement>(dom_node))
  133. return true;
  134. if (is<SVG::SVGSymbolElement>(dom_node))
  135. return true;
  136. if (is<SVG::SVGGElement>(dom_node))
  137. return true;
  138. if (is<SVG::SVGMaskElement>(dom_node))
  139. return true;
  140. return false;
  141. }
  142. void SVGFormattingContext::run(Box const& box, LayoutMode layout_mode, AvailableSpace const& available_space)
  143. {
  144. auto& svg_svg_element = verify_cast<SVG::SVGSVGElement>(*box.dom_node());
  145. auto svg_box_state = m_state.get(box);
  146. auto root_offset = svg_box_state.offset;
  147. box.for_each_child_of_type<BlockContainer>([&](BlockContainer const& child_box) {
  148. if (is<SVG::SVGForeignObjectElement>(child_box.dom_node())) {
  149. Layout::BlockFormattingContext bfc(m_state, child_box, this);
  150. bfc.run(child_box, LayoutMode::Normal, available_space);
  151. auto& child_state = m_state.get_mutable(child_box);
  152. child_state.set_content_offset(child_state.offset.translated(root_offset));
  153. }
  154. return IterationDecision::Continue;
  155. });
  156. auto compute_viewbox_transform = [&](auto const& viewbox) -> Gfx::AffineTransform {
  157. if (!viewbox.has_value())
  158. return {};
  159. // FIXME: This should allow just one of width or height to be specified.
  160. // E.g. We should be able to layout <svg width="100%"> where height is unspecified/auto.
  161. if (!svg_box_state.has_definite_width() || !svg_box_state.has_definite_height()) {
  162. dbgln_if(LIBWEB_CSS_DEBUG, "FIXME: Attempting to layout indefinitely sized SVG with a viewbox -- this likely won't work!");
  163. }
  164. auto scale_width = svg_box_state.has_definite_width() ? svg_box_state.content_width() / viewbox->width : 1;
  165. auto scale_height = svg_box_state.has_definite_height() ? svg_box_state.content_height() / viewbox->height : 1;
  166. // The initial value for preserveAspectRatio is xMidYMid meet.
  167. auto preserve_aspect_ratio = svg_svg_element.preserve_aspect_ratio().value_or(SVG::PreserveAspectRatio {});
  168. auto viewbox_offset_and_scale = scale_and_align_viewbox_content(preserve_aspect_ratio, *viewbox, { scale_width, scale_height }, svg_box_state);
  169. CSSPixelPoint offset = viewbox_offset_and_scale.offset;
  170. return Gfx::AffineTransform {}.translate(offset.to_type<float>()).scale(viewbox_offset_and_scale.scale_factor, viewbox_offset_and_scale.scale_factor).translate({ -viewbox->min_x, -viewbox->min_y });
  171. };
  172. box.for_each_in_subtree([&](Node const& descendant) {
  173. if (is<SVGGraphicsBox>(descendant)) {
  174. auto const& graphics_box = static_cast<SVGGraphicsBox const&>(descendant);
  175. auto& dom_node = const_cast<SVGGraphicsBox&>(graphics_box).dom_node();
  176. auto viewbox = dom_node.view_box();
  177. // https://svgwg.org/svg2-draft/coords.html#ViewBoxAttribute
  178. if (viewbox.has_value()) {
  179. if (viewbox->width < 0 || viewbox->height < 0) {
  180. // A negative value for <width> or <height> is an error and invalidates the ‘viewBox’ attribute.
  181. viewbox = {};
  182. } else if (viewbox->width == 0 || viewbox->height == 0) {
  183. // A value of zero disables rendering of the element.
  184. return IterationDecision::Continue;
  185. }
  186. }
  187. auto& graphics_box_state = m_state.get_mutable(graphics_box);
  188. auto svg_transform = dom_node.get_transform();
  189. Gfx::AffineTransform viewbox_transform = compute_viewbox_transform(viewbox);
  190. graphics_box_state.set_computed_svg_transforms(Painting::SVGGraphicsPaintable::ComputedTransforms(viewbox_transform, svg_transform));
  191. auto to_css_pixels_transform = Gfx::AffineTransform {}.multiply(viewbox_transform).multiply(svg_transform);
  192. Gfx::Path path;
  193. if (is<SVGGeometryBox>(descendant)) {
  194. path = static_cast<SVG::SVGGeometryElement&>(dom_node).get_path();
  195. } else if (is<SVGTextBox>(descendant)) {
  196. auto& text_element = static_cast<SVG::SVGTextPositioningElement&>(dom_node);
  197. auto& font = graphics_box.font();
  198. auto text_contents = text_element.text_contents();
  199. Utf8View text_utf8 { text_contents };
  200. auto text_width = font.width(text_utf8);
  201. auto text_offset = text_element.get_offset();
  202. // https://svgwg.org/svg2-draft/text.html#TextAnchoringProperties
  203. switch (text_element.text_anchor().value_or(SVG::TextAnchor::Start)) {
  204. case SVG::TextAnchor::Start:
  205. // The rendered characters are aligned such that the start of the resulting rendered text is at the initial
  206. // current text position.
  207. break;
  208. case SVG::TextAnchor::Middle: {
  209. // The rendered characters are shifted such that the geometric middle of the resulting rendered text
  210. // (determined from the initial and final current text position before applying the text-anchor property)
  211. // is at the initial current text position.
  212. text_offset.translate_by(-text_width / 2, 0);
  213. break;
  214. }
  215. case SVG::TextAnchor::End: {
  216. // The rendered characters are shifted such that the end of the resulting rendered text (final current text
  217. // position before applying the text-anchor property) is at the initial current text position.
  218. text_offset.translate_by(-text_width, 0);
  219. break;
  220. }
  221. default:
  222. VERIFY_NOT_REACHED();
  223. }
  224. path.move_to(text_offset);
  225. path.text(text_utf8, font);
  226. }
  227. auto path_bounding_box = to_css_pixels_transform.map(path.bounding_box()).to_type<CSSPixels>();
  228. // Stroke increases the path's size by stroke_width/2 per side.
  229. CSSPixels stroke_width = CSSPixels::nearest_value_for(graphics_box.dom_node().visible_stroke_width() * viewbox_transform.x_scale());
  230. path_bounding_box.inflate(stroke_width, stroke_width);
  231. graphics_box_state.set_content_offset(path_bounding_box.top_left());
  232. graphics_box_state.set_content_width(path_bounding_box.width());
  233. graphics_box_state.set_content_height(path_bounding_box.height());
  234. graphics_box_state.set_computed_svg_path(move(path));
  235. } else if (is<SVGSVGBox>(descendant)) {
  236. SVGFormattingContext nested_context(m_state, static_cast<SVGSVGBox const&>(descendant), this);
  237. nested_context.run(static_cast<SVGSVGBox const&>(descendant), layout_mode, available_space);
  238. }
  239. return IterationDecision::Continue;
  240. });
  241. // https://svgwg.org/svg2-draft/struct.html#Groups
  242. // 5.2. Grouping: the ‘g’ element
  243. // The ‘g’ element is a container element for grouping together related graphics elements.
  244. box.for_each_in_subtree_of_type<Box>([&](Box const& descendant) {
  245. if (is_container_element(descendant)) {
  246. Gfx::BoundingBox<CSSPixels> bounding_box;
  247. descendant.for_each_in_subtree_of_type<Box>([&](Box const& child_of_svg_container) {
  248. auto& box_state = m_state.get(child_of_svg_container);
  249. bounding_box.add_point(box_state.offset);
  250. bounding_box.add_point(box_state.offset.translated(box_state.content_width(), box_state.content_height()));
  251. return IterationDecision::Continue;
  252. });
  253. auto& box_state = m_state.get_mutable(descendant);
  254. box_state.set_content_x(bounding_box.x());
  255. box_state.set_content_y(bounding_box.y());
  256. box_state.set_content_width(bounding_box.width());
  257. box_state.set_content_height(bounding_box.height());
  258. }
  259. return IterationDecision::Continue;
  260. });
  261. }
  262. }