SVGGraphicsElement.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. /*
  2. * Copyright (c) 2020, Matthew Olsson <mattco@serenityos.org>
  3. * Copyright (c) 2021-2022, Sam Atkins <atkinssj@serenityos.org>
  4. * Copyright (c) 2023, MacDue <macdue@dueutil.tech>
  5. * Copyright (c) 2023, Andreas Kling <andreas@ladybird.org>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <LibWeb/Bindings/Intrinsics.h>
  10. #include <LibWeb/Bindings/SVGGraphicsElementPrototype.h>
  11. #include <LibWeb/CSS/Parser/Parser.h>
  12. #include <LibWeb/DOM/Document.h>
  13. #include <LibWeb/Layout/Node.h>
  14. #include <LibWeb/Painting/PaintStyle.h>
  15. #include <LibWeb/Painting/PaintableBox.h>
  16. #include <LibWeb/Painting/SVGGraphicsPaintable.h>
  17. #include <LibWeb/SVG/AttributeNames.h>
  18. #include <LibWeb/SVG/AttributeParser.h>
  19. #include <LibWeb/SVG/SVGClipPathElement.h>
  20. #include <LibWeb/SVG/SVGGradientElement.h>
  21. #include <LibWeb/SVG/SVGGraphicsElement.h>
  22. #include <LibWeb/SVG/SVGMaskElement.h>
  23. #include <LibWeb/SVG/SVGSVGElement.h>
  24. #include <LibWeb/SVG/SVGSymbolElement.h>
  25. namespace Web::SVG {
  26. SVGGraphicsElement::SVGGraphicsElement(DOM::Document& document, DOM::QualifiedName qualified_name)
  27. : SVGElement(document, move(qualified_name))
  28. {
  29. }
  30. void SVGGraphicsElement::initialize(JS::Realm& realm)
  31. {
  32. Base::initialize(realm);
  33. WEB_SET_PROTOTYPE_FOR_INTERFACE(SVGGraphicsElement);
  34. }
  35. void SVGGraphicsElement::attribute_changed(FlyString const& name, Optional<String> const& old_value, Optional<String> const& value)
  36. {
  37. SVGElement::attribute_changed(name, old_value, value);
  38. if (name == "transform"sv) {
  39. auto transform_list = AttributeParser::parse_transform(value.value_or(String {}));
  40. if (transform_list.has_value())
  41. m_transform = transform_from_transform_list(*transform_list);
  42. // FIXME: This should only invalidate the contents of the SVG.
  43. document().invalidate_layout_tree();
  44. }
  45. }
  46. Optional<Painting::PaintStyle> SVGGraphicsElement::svg_paint_computed_value_to_gfx_paint_style(SVGPaintContext const& paint_context, Optional<CSS::SVGPaint> const& paint_value) const
  47. {
  48. // FIXME: This entire function is an ad-hoc hack:
  49. if (!paint_value.has_value() || !paint_value->is_url())
  50. return {};
  51. if (auto gradient = try_resolve_url_to<SVG::SVGGradientElement const>(paint_value->as_url()))
  52. return gradient->to_gfx_paint_style(paint_context);
  53. return {};
  54. }
  55. Optional<Painting::PaintStyle> SVGGraphicsElement::fill_paint_style(SVGPaintContext const& paint_context) const
  56. {
  57. if (!layout_node())
  58. return {};
  59. return svg_paint_computed_value_to_gfx_paint_style(paint_context, layout_node()->computed_values().fill());
  60. }
  61. Optional<Painting::PaintStyle> SVGGraphicsElement::stroke_paint_style(SVGPaintContext const& paint_context) const
  62. {
  63. if (!layout_node())
  64. return {};
  65. return svg_paint_computed_value_to_gfx_paint_style(paint_context, layout_node()->computed_values().stroke());
  66. }
  67. JS::GCPtr<SVG::SVGMaskElement const> SVGGraphicsElement::mask() const
  68. {
  69. auto const& mask_reference = layout_node()->computed_values().mask();
  70. if (!mask_reference.has_value())
  71. return {};
  72. return try_resolve_url_to<SVG::SVGMaskElement const>(mask_reference->url());
  73. }
  74. JS::GCPtr<SVG::SVGClipPathElement const> SVGGraphicsElement::clip_path() const
  75. {
  76. auto const& clip_path_reference = layout_node()->computed_values().clip_path();
  77. if (!clip_path_reference.has_value() || !clip_path_reference->is_url())
  78. return {};
  79. return try_resolve_url_to<SVG::SVGClipPathElement const>(clip_path_reference->url());
  80. }
  81. Gfx::AffineTransform transform_from_transform_list(ReadonlySpan<Transform> transform_list)
  82. {
  83. Gfx::AffineTransform affine_transform;
  84. for (auto& transform : transform_list) {
  85. transform.operation.visit(
  86. [&](Transform::Translate const& translate) {
  87. affine_transform.multiply(Gfx::AffineTransform {}.translate({ translate.x, translate.y }));
  88. },
  89. [&](Transform::Scale const& scale) {
  90. affine_transform.multiply(Gfx::AffineTransform {}.scale({ scale.x, scale.y }));
  91. },
  92. [&](Transform::Rotate const& rotate) {
  93. Gfx::AffineTransform translate_transform;
  94. affine_transform.multiply(
  95. Gfx::AffineTransform {}
  96. .translate({ rotate.x, rotate.y })
  97. .rotate_radians(AK::to_radians(rotate.a))
  98. .translate({ -rotate.x, -rotate.y }));
  99. },
  100. [&](Transform::SkewX const& skew_x) {
  101. affine_transform.multiply(Gfx::AffineTransform {}.skew_radians(AK::to_radians(skew_x.a), 0));
  102. },
  103. [&](Transform::SkewY const& skew_y) {
  104. affine_transform.multiply(Gfx::AffineTransform {}.skew_radians(0, AK::to_radians(skew_y.a)));
  105. },
  106. [&](Transform::Matrix const& matrix) {
  107. affine_transform.multiply(Gfx::AffineTransform {
  108. matrix.a, matrix.b, matrix.c, matrix.d, matrix.e, matrix.f });
  109. });
  110. }
  111. return affine_transform;
  112. }
  113. Gfx::AffineTransform SVGGraphicsElement::get_transform() const
  114. {
  115. Gfx::AffineTransform transform = m_transform;
  116. for (auto* svg_ancestor = shadow_including_first_ancestor_of_type<SVGGraphicsElement>(); svg_ancestor; svg_ancestor = svg_ancestor->shadow_including_first_ancestor_of_type<SVGGraphicsElement>()) {
  117. transform = Gfx::AffineTransform { svg_ancestor->element_transform() }.multiply(transform);
  118. }
  119. return transform;
  120. }
  121. struct NamedPropertyID {
  122. NamedPropertyID(CSS::PropertyID property_id)
  123. : id(property_id)
  124. , name(CSS::string_from_property_id(property_id))
  125. {
  126. }
  127. CSS::PropertyID id;
  128. StringView name;
  129. };
  130. void SVGGraphicsElement::apply_presentational_hints(CSS::StyleProperties& style) const
  131. {
  132. static Array const attribute_style_properties {
  133. // FIXME: The `fill` attribute and CSS `fill` property are not the same! But our support is limited enough that they are equivalent for now.
  134. NamedPropertyID(CSS::PropertyID::Fill),
  135. // FIXME: The `stroke` attribute and CSS `stroke` property are not the same! But our support is limited enough that they are equivalent for now.
  136. NamedPropertyID(CSS::PropertyID::Stroke),
  137. NamedPropertyID(CSS::PropertyID::StrokeWidth),
  138. NamedPropertyID(CSS::PropertyID::FillRule),
  139. NamedPropertyID(CSS::PropertyID::FillOpacity),
  140. NamedPropertyID(CSS::PropertyID::StrokeOpacity),
  141. NamedPropertyID(CSS::PropertyID::Opacity),
  142. NamedPropertyID(CSS::PropertyID::TextAnchor),
  143. NamedPropertyID(CSS::PropertyID::FontSize),
  144. NamedPropertyID(CSS::PropertyID::Mask),
  145. NamedPropertyID(CSS::PropertyID::MaskType),
  146. NamedPropertyID(CSS::PropertyID::ClipPath),
  147. NamedPropertyID(CSS::PropertyID::ClipRule),
  148. NamedPropertyID(CSS::PropertyID::Display),
  149. };
  150. CSS::Parser::ParsingContext parsing_context { document(), CSS::Parser::ParsingContext::Mode::SVGPresentationAttribute };
  151. for_each_attribute([&](auto& name, auto& value) {
  152. for (auto property : attribute_style_properties) {
  153. if (!name.equals_ignoring_ascii_case(property.name))
  154. continue;
  155. if (auto style_value = parse_css_value(parsing_context, value, property.id))
  156. style.set_property(property.id, style_value.release_nonnull());
  157. break;
  158. }
  159. });
  160. }
  161. static FillRule to_svg_fill_rule(CSS::FillRule fill_rule)
  162. {
  163. switch (fill_rule) {
  164. case CSS::FillRule::Nonzero:
  165. return FillRule::Nonzero;
  166. case CSS::FillRule::Evenodd:
  167. return FillRule::Evenodd;
  168. default:
  169. VERIFY_NOT_REACHED();
  170. }
  171. }
  172. Optional<FillRule> SVGGraphicsElement::fill_rule() const
  173. {
  174. if (!layout_node())
  175. return {};
  176. return to_svg_fill_rule(layout_node()->computed_values().fill_rule());
  177. }
  178. Optional<ClipRule> SVGGraphicsElement::clip_rule() const
  179. {
  180. if (!layout_node())
  181. return {};
  182. return to_svg_fill_rule(layout_node()->computed_values().clip_rule());
  183. }
  184. Optional<Gfx::Color> SVGGraphicsElement::fill_color() const
  185. {
  186. if (!layout_node())
  187. return {};
  188. // FIXME: In the working-draft spec, `fill` is intended to be a shorthand, with `fill-color`
  189. // being what we actually want to use. But that's not final or widely supported yet.
  190. return layout_node()->computed_values().fill().map([&](auto& paint) -> Gfx::Color {
  191. if (!paint.is_color())
  192. return Color::Black;
  193. return paint.as_color();
  194. });
  195. }
  196. Optional<Gfx::Color> SVGGraphicsElement::stroke_color() const
  197. {
  198. if (!layout_node())
  199. return {};
  200. // FIXME: In the working-draft spec, `stroke` is intended to be a shorthand, with `stroke-color`
  201. // being what we actually want to use. But that's not final or widely supported yet.
  202. return layout_node()->computed_values().stroke().map([](auto& paint) -> Gfx::Color {
  203. if (!paint.is_color())
  204. return Color::Black;
  205. return paint.as_color();
  206. });
  207. }
  208. Optional<float> SVGGraphicsElement::fill_opacity() const
  209. {
  210. if (!layout_node())
  211. return {};
  212. return layout_node()->computed_values().fill_opacity();
  213. }
  214. Optional<CSS::StrokeLinecap> SVGGraphicsElement::stroke_linecap() const
  215. {
  216. if (!layout_node())
  217. return {};
  218. return layout_node()->computed_values().stroke_linecap();
  219. }
  220. Optional<float> SVGGraphicsElement::stroke_opacity() const
  221. {
  222. if (!layout_node())
  223. return {};
  224. return layout_node()->computed_values().stroke_opacity();
  225. }
  226. Optional<float> SVGGraphicsElement::stroke_width() const
  227. {
  228. if (!layout_node())
  229. return {};
  230. // FIXME: Converting to pixels isn't really correct - values should be in "user units"
  231. // https://svgwg.org/svg2-draft/coords.html#TermUserUnits
  232. auto width = layout_node()->computed_values().stroke_width();
  233. // Resolved relative to the "Scaled viewport size": https://www.w3.org/TR/2017/WD-fill-stroke-3-20170413/#scaled-viewport-size
  234. // FIXME: This isn't right, but it's something.
  235. CSSPixels viewport_width = 0;
  236. CSSPixels viewport_height = 0;
  237. if (auto* svg_svg_element = shadow_including_first_ancestor_of_type<SVGSVGElement>()) {
  238. if (auto svg_svg_layout_node = svg_svg_element->layout_node()) {
  239. viewport_width = svg_svg_layout_node->computed_values().width().to_px(*svg_svg_layout_node, 0);
  240. viewport_height = svg_svg_layout_node->computed_values().height().to_px(*svg_svg_layout_node, 0);
  241. }
  242. }
  243. auto scaled_viewport_size = (viewport_width + viewport_height) * CSSPixels(0.5);
  244. return width.to_px(*layout_node(), scaled_viewport_size).to_double();
  245. }
  246. // https://svgwg.org/svg2-draft/types.html#__svg__SVGGraphicsElement__getBBox
  247. JS::NonnullGCPtr<Geometry::DOMRect> SVGGraphicsElement::get_b_box(Optional<SVGBoundingBoxOptions>)
  248. {
  249. // FIXME: It should be possible to compute this without layout updates. The bounding box is within the
  250. // SVG coordinate space (before any viewbox or other transformations), so it should be possible to
  251. // calculate this from SVG geometry without a full layout tree (at least for simple cases).
  252. // See: https://svgwg.org/svg2-draft/coords.html#BoundingBoxes
  253. const_cast<DOM::Document&>(document()).update_layout();
  254. if (!layout_node())
  255. return Geometry::DOMRect::create(realm());
  256. // Invert the SVG -> screen space transform.
  257. auto owner_svg_element = this->owner_svg_element();
  258. if (!owner_svg_element)
  259. return Geometry::DOMRect::create(realm());
  260. auto svg_element_rect = owner_svg_element->paintable_box()->absolute_rect();
  261. auto inverse_transform = static_cast<Painting::SVGGraphicsPaintable&>(*paintable_box()).computed_transforms().svg_to_css_pixels_transform().inverse();
  262. auto translated_rect = paintable_box()->absolute_rect().to_type<float>().translated(-svg_element_rect.location().to_type<float>());
  263. if (inverse_transform.has_value())
  264. translated_rect = inverse_transform->map(translated_rect);
  265. return Geometry::DOMRect::create(realm(), translated_rect);
  266. }
  267. JS::NonnullGCPtr<SVGAnimatedTransformList> SVGGraphicsElement::transform() const
  268. {
  269. dbgln("(STUBBED) SVGGraphicsElement::transform(). Called on: {}", debug_description());
  270. auto base_val = SVGTransformList::create(realm());
  271. auto anim_val = SVGTransformList::create(realm());
  272. return SVGAnimatedTransformList::create(realm(), base_val, anim_val);
  273. }
  274. }