SVGFormattingContext.cpp 15 KB

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