SVGFormattingContext.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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, Gfx::AffineTransform parent_viewbox_transform)
  27. : FormattingContext(Type::SVG, state, box, parent)
  28. , m_parent_viewbox_transform(parent_viewbox_transform)
  29. {
  30. }
  31. SVGFormattingContext::~SVGFormattingContext() = default;
  32. CSSPixels SVGFormattingContext::automatic_content_width() const
  33. {
  34. return 0;
  35. }
  36. CSSPixels SVGFormattingContext::automatic_content_height() const
  37. {
  38. return 0;
  39. }
  40. struct ViewBoxTransform {
  41. CSSPixelPoint offset;
  42. double scale_factor;
  43. };
  44. // https://svgwg.org/svg2-draft/coords.html#PreserveAspectRatioAttribute
  45. static ViewBoxTransform scale_and_align_viewbox_content(SVG::PreserveAspectRatio const& preserve_aspect_ratio,
  46. SVG::ViewBox const& view_box, Gfx::FloatSize viewbox_scale, auto const& svg_box_state)
  47. {
  48. ViewBoxTransform viewbox_transform {};
  49. switch (preserve_aspect_ratio.meet_or_slice) {
  50. case SVG::PreserveAspectRatio::MeetOrSlice::Meet:
  51. // meet (the default) - Scale the graphic such that:
  52. // - aspect ratio is preserved
  53. // - the entire ‘viewBox’ is visible within the SVG viewport
  54. // - the ‘viewBox’ is scaled up as much as possible, while still meeting the other criteria
  55. viewbox_transform.scale_factor = min(viewbox_scale.width(), viewbox_scale.height());
  56. break;
  57. case SVG::PreserveAspectRatio::MeetOrSlice::Slice:
  58. // slice - Scale the graphic such that:
  59. // aspect ratio is preserved
  60. // the entire SVG viewport is covered by the ‘viewBox’
  61. // the ‘viewBox’ is scaled down as much as possible, while still meeting the other criteria
  62. viewbox_transform.scale_factor = max(viewbox_scale.width(), viewbox_scale.height());
  63. break;
  64. default:
  65. VERIFY_NOT_REACHED();
  66. }
  67. // Handle X alignment:
  68. if (svg_box_state.has_definite_width()) {
  69. switch (preserve_aspect_ratio.align) {
  70. case SVG::PreserveAspectRatio::Align::xMinYMin:
  71. case SVG::PreserveAspectRatio::Align::xMinYMid:
  72. case SVG::PreserveAspectRatio::Align::xMinYMax:
  73. // Align the <min-x> of the element's ‘viewBox’ with the smallest X value of the SVG viewport.
  74. viewbox_transform.offset.translate_by(0, 0);
  75. break;
  76. case SVG::PreserveAspectRatio::Align::None: {
  77. // Do not force uniform scaling. Scale the graphic content of the given element non-uniformly
  78. // if necessary such that the element's bounding box exactly matches the SVG viewport rectangle.
  79. // FIXME: None is unimplemented (treat as xMidYMid)
  80. [[fallthrough]];
  81. }
  82. case SVG::PreserveAspectRatio::Align::xMidYMin:
  83. case SVG::PreserveAspectRatio::Align::xMidYMid:
  84. case SVG::PreserveAspectRatio::Align::xMidYMax:
  85. // Align the midpoint X value of the element's ‘viewBox’ with the midpoint X value of the SVG viewport.
  86. viewbox_transform.offset.translate_by((svg_box_state.content_width() - CSSPixels::nearest_value_for(view_box.width * viewbox_transform.scale_factor)) / 2, 0);
  87. break;
  88. case SVG::PreserveAspectRatio::Align::xMaxYMin:
  89. case SVG::PreserveAspectRatio::Align::xMaxYMid:
  90. case SVG::PreserveAspectRatio::Align::xMaxYMax:
  91. // Align the <min-x>+<width> of the element's ‘viewBox’ with the maximum X value of the SVG viewport.
  92. viewbox_transform.offset.translate_by((svg_box_state.content_width() - CSSPixels::nearest_value_for(view_box.width * viewbox_transform.scale_factor)), 0);
  93. break;
  94. default:
  95. VERIFY_NOT_REACHED();
  96. }
  97. }
  98. if (svg_box_state.has_definite_width()) {
  99. switch (preserve_aspect_ratio.align) {
  100. case SVG::PreserveAspectRatio::Align::xMinYMin:
  101. case SVG::PreserveAspectRatio::Align::xMidYMin:
  102. case SVG::PreserveAspectRatio::Align::xMaxYMin:
  103. // Align the <min-y> of the element's ‘viewBox’ with the smallest Y value of the SVG viewport.
  104. viewbox_transform.offset.translate_by(0, 0);
  105. break;
  106. case SVG::PreserveAspectRatio::Align::None: {
  107. // Do not force uniform scaling. Scale the graphic content of the given element non-uniformly
  108. // if necessary such that the element's bounding box exactly matches the SVG viewport rectangle.
  109. // FIXME: None is unimplemented (treat as xMidYMid)
  110. [[fallthrough]];
  111. }
  112. case SVG::PreserveAspectRatio::Align::xMinYMid:
  113. case SVG::PreserveAspectRatio::Align::xMidYMid:
  114. case SVG::PreserveAspectRatio::Align::xMaxYMid:
  115. // Align the midpoint Y value of the element's ‘viewBox’ with the midpoint Y value of the SVG viewport.
  116. viewbox_transform.offset.translate_by(0, (svg_box_state.content_height() - CSSPixels::nearest_value_for(view_box.height * viewbox_transform.scale_factor)) / 2);
  117. break;
  118. case SVG::PreserveAspectRatio::Align::xMinYMax:
  119. case SVG::PreserveAspectRatio::Align::xMidYMax:
  120. case SVG::PreserveAspectRatio::Align::xMaxYMax:
  121. // Align the <min-y>+<height> of the element's ‘viewBox’ with the maximum Y value of the SVG viewport.
  122. viewbox_transform.offset.translate_by(0, (svg_box_state.content_height() - CSSPixels::nearest_value_for(view_box.height * viewbox_transform.scale_factor)));
  123. break;
  124. default:
  125. VERIFY_NOT_REACHED();
  126. }
  127. }
  128. return viewbox_transform;
  129. }
  130. static bool is_container_element(Node const& node)
  131. {
  132. // https://svgwg.org/svg2-draft/struct.html#GroupsOverview
  133. auto* dom_node = node.dom_node();
  134. if (!dom_node)
  135. return false;
  136. if (is<SVG::SVGUseElement>(dom_node))
  137. return true;
  138. if (is<SVG::SVGSymbolElement>(dom_node))
  139. return true;
  140. if (is<SVG::SVGGElement>(dom_node))
  141. return true;
  142. if (is<SVG::SVGMaskElement>(dom_node))
  143. return true;
  144. return false;
  145. }
  146. enum class TraversalDecision {
  147. Continue,
  148. SkipChildrenAndContinue,
  149. Break,
  150. };
  151. // FIXME: Add TraversalDecision::SkipChildrenAndContinue to TreeNode's implementation.
  152. template<typename Callback>
  153. static TraversalDecision for_each_in_inclusive_subtree(Layout::Node const& node, Callback callback)
  154. {
  155. if (auto decision = callback(node); decision != TraversalDecision::Continue)
  156. return decision;
  157. for (auto* child = node.first_child(); child; child = child->next_sibling()) {
  158. if (for_each_in_inclusive_subtree(*child, callback) == TraversalDecision::Break)
  159. return TraversalDecision::Break;
  160. }
  161. return TraversalDecision::Continue;
  162. }
  163. // FIXME: Add TraversalDecision::SkipChildrenAndContinue to TreeNode's implementation.
  164. template<typename Callback>
  165. static TraversalDecision for_each_in_subtree(Layout::Node const& node, Callback callback)
  166. {
  167. for (auto* child = node.first_child(); child; child = child->next_sibling()) {
  168. if (for_each_in_inclusive_subtree(*child, callback) == TraversalDecision::Break)
  169. return TraversalDecision::Break;
  170. }
  171. return TraversalDecision::Continue;
  172. }
  173. void SVGFormattingContext::run(Box const& box, LayoutMode layout_mode, AvailableSpace const& available_space)
  174. {
  175. auto& svg_viewport = dynamic_cast<SVG::SVGViewport const&>(*box.dom_node());
  176. auto& svg_box_state = m_state.get_mutable(box);
  177. auto viewbox = svg_viewport.view_box();
  178. // https://svgwg.org/svg2-draft/coords.html#ViewBoxAttribute
  179. if (viewbox.has_value()) {
  180. if (viewbox->width < 0 || viewbox->height < 0) {
  181. // A negative value for <width> or <height> is an error and invalidates the ‘viewBox’ attribute.
  182. viewbox = {};
  183. } else if (viewbox->width == 0 || viewbox->height == 0) {
  184. // A value of zero disables rendering of the element.
  185. return;
  186. }
  187. }
  188. auto viewbox_transform = [&] {
  189. if (!viewbox.has_value())
  190. return m_parent_viewbox_transform;
  191. // FIXME: This should allow just one of width or height to be specified.
  192. // E.g. We should be able to layout <svg width="100%"> where height is unspecified/auto.
  193. if (!svg_box_state.has_definite_width() || !svg_box_state.has_definite_height()) {
  194. dbgln_if(LIBWEB_CSS_DEBUG, "FIXME: Attempting to layout indefinitely sized SVG with a viewbox -- this likely won't work!");
  195. }
  196. auto scale_width = svg_box_state.has_definite_width() ? svg_box_state.content_width() / viewbox->width : 1;
  197. auto scale_height = svg_box_state.has_definite_height() ? svg_box_state.content_height() / viewbox->height : 1;
  198. // The initial value for preserveAspectRatio is xMidYMid meet.
  199. auto preserve_aspect_ratio = svg_viewport.preserve_aspect_ratio().value_or(SVG::PreserveAspectRatio {});
  200. auto viewbox_offset_and_scale = scale_and_align_viewbox_content(preserve_aspect_ratio, *viewbox, { scale_width, scale_height }, svg_box_state);
  201. CSSPixelPoint offset = viewbox_offset_and_scale.offset;
  202. return Gfx::AffineTransform { m_parent_viewbox_transform }.multiply(Gfx::AffineTransform {}
  203. .translate(offset.to_type<float>())
  204. .scale(viewbox_offset_and_scale.scale_factor, viewbox_offset_and_scale.scale_factor)
  205. .translate({ -viewbox->min_x, -viewbox->min_y }));
  206. }();
  207. if (svg_box_state.has_definite_width() && svg_box_state.has_definite_height()) {
  208. // Scale the box of the viewport based on the parent's viewBox transform.
  209. // The viewBox transform is always just a simple scale + offset.
  210. // FIXME: Avoid converting SVG box to floats.
  211. Gfx::FloatRect svg_rect = { svg_box_state.offset.to_type<float>(),
  212. { float(svg_box_state.content_width()), float(svg_box_state.content_height()) } };
  213. svg_rect = m_parent_viewbox_transform.map(svg_rect);
  214. svg_box_state.set_content_offset(svg_rect.location().to_type<CSSPixels>());
  215. svg_box_state.set_content_width(CSSPixels(svg_rect.width()));
  216. svg_box_state.set_content_height(CSSPixels(svg_rect.height()));
  217. }
  218. auto root_offset = svg_box_state.offset;
  219. box.for_each_child_of_type<BlockContainer>([&](BlockContainer const& child_box) {
  220. if (is<SVG::SVGForeignObjectElement>(child_box.dom_node())) {
  221. Layout::BlockFormattingContext bfc(m_state, child_box, this);
  222. bfc.run(child_box, LayoutMode::Normal, available_space);
  223. auto& child_state = m_state.get_mutable(child_box);
  224. child_state.set_content_offset(child_state.offset.translated(root_offset));
  225. }
  226. return IterationDecision::Continue;
  227. });
  228. for_each_in_subtree(box, [&](Node const& descendant) {
  229. if (is<SVG::SVGViewport>(descendant.dom_node())) {
  230. // Layout for a nested SVG viewport.
  231. // https://svgwg.org/svg2-draft/coords.html#EstablishingANewSVGViewport.
  232. SVGFormattingContext nested_context(m_state, static_cast<Box const&>(descendant), this, viewbox_transform);
  233. auto& nested_viewport_state = m_state.get_mutable(static_cast<Box const&>(descendant));
  234. auto viewport_width = [&] {
  235. if (viewbox.has_value())
  236. return CSSPixels::nearest_value_for(viewbox->width);
  237. if (svg_box_state.has_definite_width())
  238. return svg_box_state.content_width();
  239. dbgln_if(LIBWEB_CSS_DEBUG, "FIXME: Failed to resolve width of SVG viewport!");
  240. return CSSPixels {};
  241. }();
  242. auto viewport_height = [&] {
  243. if (viewbox.has_value())
  244. return CSSPixels::nearest_value_for(viewbox->height);
  245. if (svg_box_state.has_definite_height())
  246. return svg_box_state.content_height();
  247. dbgln_if(LIBWEB_CSS_DEBUG, "FIXME: Failed to resolve height of SVG viewport!");
  248. return CSSPixels {};
  249. }();
  250. auto resolve_dimension = [](auto& node, auto size, auto reference_value) {
  251. // The value auto for width and height on the ‘svg’ element is treated as 100%.
  252. // https://svgwg.org/svg2-draft/geometry.html#Sizing
  253. if (size.is_auto())
  254. return reference_value;
  255. return size.to_px(node, reference_value);
  256. };
  257. auto nested_viewport_x = descendant.computed_values().x().to_px(descendant, viewport_width);
  258. auto nested_viewport_y = descendant.computed_values().y().to_px(descendant, viewport_height);
  259. auto nested_viewport_width = resolve_dimension(descendant, descendant.computed_values().width(), viewport_width);
  260. auto nested_viewport_height = resolve_dimension(descendant, descendant.computed_values().height(), viewport_height);
  261. nested_viewport_state.set_content_offset({ nested_viewport_x, nested_viewport_y });
  262. nested_viewport_state.set_content_width(nested_viewport_width);
  263. nested_viewport_state.set_content_height(nested_viewport_height);
  264. nested_context.run(static_cast<Box const&>(descendant), layout_mode, available_space);
  265. return TraversalDecision::SkipChildrenAndContinue;
  266. }
  267. if (is<SVGGraphicsBox>(descendant)) {
  268. auto const& graphics_box = static_cast<SVGGraphicsBox const&>(descendant);
  269. auto& dom_node = const_cast<SVGGraphicsBox&>(graphics_box).dom_node();
  270. auto& graphics_box_state = m_state.get_mutable(graphics_box);
  271. auto svg_transform = dom_node.get_transform();
  272. graphics_box_state.set_computed_svg_transforms(Painting::SVGGraphicsPaintable::ComputedTransforms(viewbox_transform, svg_transform));
  273. auto to_css_pixels_transform = Gfx::AffineTransform {}.multiply(viewbox_transform).multiply(svg_transform);
  274. Gfx::Path path;
  275. if (is<SVGGeometryBox>(descendant)) {
  276. path = static_cast<SVG::SVGGeometryElement&>(dom_node).get_path();
  277. } else if (is<SVGTextBox>(descendant)) {
  278. auto& text_element = static_cast<SVG::SVGTextPositioningElement&>(dom_node);
  279. auto& font = graphics_box.first_available_font();
  280. auto text_contents = text_element.text_contents();
  281. Utf8View text_utf8 { text_contents };
  282. auto text_width = font.width(text_utf8);
  283. auto text_offset = text_element.get_offset();
  284. // https://svgwg.org/svg2-draft/text.html#TextAnchoringProperties
  285. switch (text_element.text_anchor().value_or(SVG::TextAnchor::Start)) {
  286. case SVG::TextAnchor::Start:
  287. // The rendered characters are aligned such that the start of the resulting rendered text is at the initial
  288. // current text position.
  289. break;
  290. case SVG::TextAnchor::Middle: {
  291. // The rendered characters are shifted such that the geometric middle of the resulting rendered text
  292. // (determined from the initial and final current text position before applying the text-anchor property)
  293. // is at the initial current text position.
  294. text_offset.translate_by(-text_width / 2, 0);
  295. break;
  296. }
  297. case SVG::TextAnchor::End: {
  298. // The rendered characters are shifted such that the end of the resulting rendered text (final current text
  299. // position before applying the text-anchor property) is at the initial current text position.
  300. text_offset.translate_by(-text_width, 0);
  301. break;
  302. }
  303. default:
  304. VERIFY_NOT_REACHED();
  305. }
  306. path.move_to(text_offset);
  307. path.text(text_utf8, font);
  308. } else if (is<SVGTextPathBox>(descendant)) {
  309. auto& text_path_element = static_cast<SVG::SVGTextPathElement&>(dom_node);
  310. auto path_or_shape = text_path_element.path_or_shape();
  311. if (!path_or_shape)
  312. return TraversalDecision::Continue;
  313. auto& font = graphics_box.first_available_font();
  314. auto text_contents = text_path_element.text_contents();
  315. Utf8View text_utf8 { text_contents };
  316. auto shape_path = const_cast<SVG::SVGGeometryElement&>(*path_or_shape).get_path();
  317. path = shape_path.place_text_along(text_utf8, font);
  318. }
  319. auto path_bounding_box = to_css_pixels_transform.map(path.bounding_box()).to_type<CSSPixels>();
  320. // Stroke increases the path's size by stroke_width/2 per side.
  321. CSSPixels stroke_width = CSSPixels::nearest_value_for(graphics_box.dom_node().visible_stroke_width() * viewbox_transform.x_scale());
  322. path_bounding_box.inflate(stroke_width, stroke_width);
  323. graphics_box_state.set_content_offset(path_bounding_box.top_left());
  324. graphics_box_state.set_content_width(path_bounding_box.width());
  325. graphics_box_state.set_content_height(path_bounding_box.height());
  326. graphics_box_state.set_computed_svg_path(move(path));
  327. }
  328. return TraversalDecision::Continue;
  329. });
  330. // https://svgwg.org/svg2-draft/struct.html#Groups
  331. // 5.2. Grouping: the ‘g’ element
  332. // The ‘g’ element is a container element for grouping together related graphics elements.
  333. box.for_each_in_subtree_of_type<Box>([&](Box const& descendant) {
  334. if (is_container_element(descendant)) {
  335. Gfx::BoundingBox<CSSPixels> bounding_box;
  336. descendant.for_each_in_subtree_of_type<Box>([&](Box const& child_of_svg_container) {
  337. auto& box_state = m_state.get(child_of_svg_container);
  338. bounding_box.add_point(box_state.offset);
  339. bounding_box.add_point(box_state.offset.translated(box_state.content_width(), box_state.content_height()));
  340. return IterationDecision::Continue;
  341. });
  342. auto& box_state = m_state.get_mutable(descendant);
  343. box_state.set_content_x(bounding_box.x());
  344. box_state.set_content_y(bounding_box.y());
  345. box_state.set_content_width(bounding_box.width());
  346. box_state.set_content_height(bounding_box.height());
  347. }
  348. return IterationDecision::Continue;
  349. });
  350. }
  351. }