SVGFormattingContext.cpp 15 KB

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