SVGGraphicsElement.cpp 11 KB

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