SVGFormattingContext.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. // NOTE: SVG doesn't have a "formatting context" in the spec, but this is the most
  176. // obvious way to drive SVG layout in our engine at the moment.
  177. auto& svg_viewport = dynamic_cast<SVG::SVGViewport const&>(*box.dom_node());
  178. auto& svg_box_state = m_state.get_mutable(box);
  179. // NOTE: We consider all SVG root elements to have definite size in both axes.
  180. // I'm not sure if this is good or bad, but our viewport transform logic depends on it.
  181. svg_box_state.set_has_definite_width(true);
  182. svg_box_state.set_has_definite_height(true);
  183. auto viewbox = svg_viewport.view_box();
  184. // https://svgwg.org/svg2-draft/coords.html#ViewBoxAttribute
  185. if (viewbox.has_value()) {
  186. if (viewbox->width < 0 || viewbox->height < 0) {
  187. // A negative value for <width> or <height> is an error and invalidates the ‘viewBox’ attribute.
  188. viewbox = {};
  189. } else if (viewbox->width == 0 || viewbox->height == 0) {
  190. // A value of zero disables rendering of the element.
  191. return;
  192. }
  193. }
  194. auto viewbox_transform = [&] {
  195. if (!viewbox.has_value())
  196. return m_parent_viewbox_transform;
  197. // FIXME: This should allow just one of width or height to be specified.
  198. // E.g. We should be able to layout <svg width="100%"> where height is unspecified/auto.
  199. if (!svg_box_state.has_definite_width() || !svg_box_state.has_definite_height()) {
  200. dbgln_if(LIBWEB_CSS_DEBUG, "FIXME: Attempting to layout indefinitely sized SVG with a viewbox -- this likely won't work!");
  201. }
  202. auto scale_width = svg_box_state.has_definite_width() ? svg_box_state.content_width() / viewbox->width : 1;
  203. auto scale_height = svg_box_state.has_definite_height() ? svg_box_state.content_height() / viewbox->height : 1;
  204. // The initial value for preserveAspectRatio is xMidYMid meet.
  205. auto preserve_aspect_ratio = svg_viewport.preserve_aspect_ratio().value_or(SVG::PreserveAspectRatio {});
  206. auto viewbox_offset_and_scale = scale_and_align_viewbox_content(preserve_aspect_ratio, *viewbox, { scale_width, scale_height }, svg_box_state);
  207. CSSPixelPoint offset = viewbox_offset_and_scale.offset;
  208. return Gfx::AffineTransform { m_parent_viewbox_transform }.multiply(Gfx::AffineTransform {}
  209. .translate(offset.to_type<float>())
  210. .scale(viewbox_offset_and_scale.scale_factor, viewbox_offset_and_scale.scale_factor)
  211. .translate({ -viewbox->min_x, -viewbox->min_y }));
  212. }();
  213. if (svg_box_state.has_definite_width() && svg_box_state.has_definite_height()) {
  214. // Scale the box of the viewport based on the parent's viewBox transform.
  215. // The viewBox transform is always just a simple scale + offset.
  216. // FIXME: Avoid converting SVG box to floats.
  217. Gfx::FloatRect svg_rect = { svg_box_state.offset.to_type<float>(),
  218. { float(svg_box_state.content_width()), float(svg_box_state.content_height()) } };
  219. svg_rect = m_parent_viewbox_transform.map(svg_rect);
  220. svg_box_state.set_content_offset(svg_rect.location().to_type<CSSPixels>());
  221. svg_box_state.set_content_width(CSSPixels(svg_rect.width()));
  222. svg_box_state.set_content_height(CSSPixels(svg_rect.height()));
  223. svg_box_state.set_has_definite_width(true);
  224. svg_box_state.set_has_definite_height(true);
  225. }
  226. auto root_offset = svg_box_state.offset;
  227. box.for_each_child_of_type<BlockContainer>([&](BlockContainer const& child_box) {
  228. if (is<SVG::SVGForeignObjectElement>(child_box.dom_node())) {
  229. Layout::BlockFormattingContext bfc(m_state, child_box, this);
  230. bfc.run(child_box, LayoutMode::Normal, available_space);
  231. auto& child_state = m_state.get_mutable(child_box);
  232. child_state.set_content_offset(child_state.offset.translated(root_offset));
  233. }
  234. return IterationDecision::Continue;
  235. });
  236. auto viewport_width = [&] {
  237. if (viewbox.has_value())
  238. return CSSPixels::nearest_value_for(viewbox->width);
  239. if (svg_box_state.has_definite_width())
  240. return svg_box_state.content_width();
  241. dbgln_if(LIBWEB_CSS_DEBUG, "FIXME: Failed to resolve width of SVG viewport!");
  242. return CSSPixels {};
  243. }();
  244. auto viewport_height = [&] {
  245. if (viewbox.has_value())
  246. return CSSPixels::nearest_value_for(viewbox->height);
  247. if (svg_box_state.has_definite_height())
  248. return svg_box_state.content_height();
  249. dbgln_if(LIBWEB_CSS_DEBUG, "FIXME: Failed to resolve height of SVG viewport!");
  250. return CSSPixels {};
  251. }();
  252. for_each_in_subtree(box, [&](Node const& descendant) {
  253. if (is<SVG::SVGViewport>(descendant.dom_node())) {
  254. // Layout for a nested SVG viewport.
  255. // https://svgwg.org/svg2-draft/coords.html#EstablishingANewSVGViewport.
  256. SVGFormattingContext nested_context(m_state, static_cast<Box const&>(descendant), this, viewbox_transform);
  257. auto& nested_viewport_state = m_state.get_mutable(static_cast<Box const&>(descendant));
  258. auto resolve_dimension = [](auto& node, auto size, auto reference_value) {
  259. // The value auto for width and height on the ‘svg’ element is treated as 100%.
  260. // https://svgwg.org/svg2-draft/geometry.html#Sizing
  261. if (size.is_auto())
  262. return reference_value;
  263. return size.to_px(node, reference_value);
  264. };
  265. auto nested_viewport_x = descendant.computed_values().x().to_px(descendant, viewport_width);
  266. auto nested_viewport_y = descendant.computed_values().y().to_px(descendant, viewport_height);
  267. auto nested_viewport_width = resolve_dimension(descendant, descendant.computed_values().width(), viewport_width);
  268. auto nested_viewport_height = resolve_dimension(descendant, descendant.computed_values().height(), viewport_height);
  269. nested_viewport_state.set_content_offset({ nested_viewport_x, nested_viewport_y });
  270. nested_viewport_state.set_content_width(nested_viewport_width);
  271. nested_viewport_state.set_content_height(nested_viewport_height);
  272. nested_viewport_state.set_has_definite_width(true);
  273. nested_viewport_state.set_has_definite_height(true);
  274. nested_context.run(static_cast<Box const&>(descendant), layout_mode, available_space);
  275. return TraversalDecision::SkipChildrenAndContinue;
  276. }
  277. if (is<SVGGraphicsBox>(descendant)) {
  278. auto const& graphics_box = static_cast<SVGGraphicsBox const&>(descendant);
  279. auto& dom_node = const_cast<SVGGraphicsBox&>(graphics_box).dom_node();
  280. auto& graphics_box_state = m_state.get_mutable(graphics_box);
  281. auto svg_transform = dom_node.get_transform();
  282. graphics_box_state.set_computed_svg_transforms(Painting::SVGGraphicsPaintable::ComputedTransforms(viewbox_transform, svg_transform));
  283. auto to_css_pixels_transform = Gfx::AffineTransform {}.multiply(viewbox_transform).multiply(svg_transform);
  284. Gfx::Path path;
  285. if (is<SVGGeometryBox>(descendant)) {
  286. path = static_cast<SVG::SVGGeometryElement&>(dom_node).get_path({ viewport_width, viewport_height });
  287. } else if (is<SVGTextBox>(descendant)) {
  288. auto& text_element = static_cast<SVG::SVGTextPositioningElement&>(dom_node);
  289. auto& font = graphics_box.first_available_font();
  290. auto text_contents = text_element.text_contents();
  291. Utf8View text_utf8 { text_contents };
  292. auto text_width = font.width(text_utf8);
  293. auto text_offset = text_element.get_offset();
  294. // https://svgwg.org/svg2-draft/text.html#TextAnchoringProperties
  295. switch (text_element.text_anchor().value_or(SVG::TextAnchor::Start)) {
  296. case SVG::TextAnchor::Start:
  297. // The rendered characters are aligned such that the start of the resulting rendered text is at the initial
  298. // current text position.
  299. break;
  300. case SVG::TextAnchor::Middle: {
  301. // The rendered characters are shifted such that the geometric middle of the resulting rendered text
  302. // (determined from the initial and final current text position before applying the text-anchor property)
  303. // is at the initial current text position.
  304. text_offset.translate_by(-text_width / 2, 0);
  305. break;
  306. }
  307. case SVG::TextAnchor::End: {
  308. // The rendered characters are shifted such that the end of the resulting rendered text (final current text
  309. // position before applying the text-anchor property) is at the initial current text position.
  310. text_offset.translate_by(-text_width, 0);
  311. break;
  312. }
  313. default:
  314. VERIFY_NOT_REACHED();
  315. }
  316. path.move_to(text_offset);
  317. path.text(text_utf8, font);
  318. } else if (is<SVGTextPathBox>(descendant)) {
  319. auto& text_path_element = static_cast<SVG::SVGTextPathElement&>(dom_node);
  320. auto path_or_shape = text_path_element.path_or_shape();
  321. if (!path_or_shape)
  322. return TraversalDecision::Continue;
  323. auto& font = graphics_box.first_available_font();
  324. auto text_contents = text_path_element.text_contents();
  325. Utf8View text_utf8 { text_contents };
  326. auto shape_path = const_cast<SVG::SVGGeometryElement&>(*path_or_shape).get_path({ viewport_width, viewport_height });
  327. path = shape_path.place_text_along(text_utf8, font);
  328. }
  329. auto path_bounding_box = to_css_pixels_transform.map(path.bounding_box()).to_type<CSSPixels>();
  330. // Stroke increases the path's size by stroke_width/2 per side.
  331. CSSPixels stroke_width = CSSPixels::nearest_value_for(graphics_box.dom_node().visible_stroke_width() * viewbox_transform.x_scale());
  332. path_bounding_box.inflate(stroke_width, stroke_width);
  333. graphics_box_state.set_content_offset(path_bounding_box.top_left());
  334. graphics_box_state.set_content_width(path_bounding_box.width());
  335. graphics_box_state.set_content_height(path_bounding_box.height());
  336. graphics_box_state.set_has_definite_width(true);
  337. graphics_box_state.set_has_definite_height(true);
  338. graphics_box_state.set_computed_svg_path(move(path));
  339. }
  340. return TraversalDecision::Continue;
  341. });
  342. // https://svgwg.org/svg2-draft/struct.html#Groups
  343. // 5.2. Grouping: the ‘g’ element
  344. // The ‘g’ element is a container element for grouping together related graphics elements.
  345. box.for_each_in_subtree_of_type<Box>([&](Box const& descendant) {
  346. if (is_container_element(descendant)) {
  347. Gfx::BoundingBox<CSSPixels> bounding_box;
  348. descendant.for_each_in_subtree_of_type<Box>([&](Box const& child_of_svg_container) {
  349. auto& box_state = m_state.get(child_of_svg_container);
  350. bounding_box.add_point(box_state.offset);
  351. bounding_box.add_point(box_state.offset.translated(box_state.content_width(), box_state.content_height()));
  352. return IterationDecision::Continue;
  353. });
  354. auto& box_state = m_state.get_mutable(descendant);
  355. box_state.set_content_x(bounding_box.x());
  356. box_state.set_content_y(bounding_box.y());
  357. box_state.set_content_width(bounding_box.width());
  358. box_state.set_content_height(bounding_box.height());
  359. box_state.set_has_definite_width(true);
  360. box_state.set_has_definite_height(true);
  361. }
  362. return IterationDecision::Continue;
  363. });
  364. }
  365. }