SVGGraphicsElement.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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, Optional<FlyString> const& namespace_)
  36. {
  37. Base::attribute_changed(name, old_value, value, namespace_);
  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. GC::Ptr<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. GC::Ptr<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::StrokeDashoffset),
  138. NamedPropertyID(CSS::PropertyID::StrokeLinecap),
  139. NamedPropertyID(CSS::PropertyID::StrokeLinejoin),
  140. NamedPropertyID(CSS::PropertyID::StrokeMiterlimit),
  141. NamedPropertyID(CSS::PropertyID::StrokeWidth),
  142. NamedPropertyID(CSS::PropertyID::FillRule),
  143. NamedPropertyID(CSS::PropertyID::FillOpacity),
  144. NamedPropertyID(CSS::PropertyID::StrokeOpacity),
  145. NamedPropertyID(CSS::PropertyID::Opacity),
  146. NamedPropertyID(CSS::PropertyID::TextAnchor),
  147. NamedPropertyID(CSS::PropertyID::FontSize),
  148. NamedPropertyID(CSS::PropertyID::Mask),
  149. NamedPropertyID(CSS::PropertyID::MaskType),
  150. NamedPropertyID(CSS::PropertyID::ClipPath),
  151. NamedPropertyID(CSS::PropertyID::ClipRule),
  152. NamedPropertyID(CSS::PropertyID::Display),
  153. };
  154. CSS::Parser::ParsingContext parsing_context { document(), CSS::Parser::ParsingContext::Mode::SVGPresentationAttribute };
  155. for_each_attribute([&](auto& name, auto& value) {
  156. for (auto property : attribute_style_properties) {
  157. if (!name.equals_ignoring_ascii_case(property.name))
  158. continue;
  159. if (auto style_value = parse_css_value(parsing_context, value, property.id))
  160. style.set_property(property.id, style_value.release_nonnull());
  161. break;
  162. }
  163. });
  164. }
  165. static FillRule to_svg_fill_rule(CSS::FillRule fill_rule)
  166. {
  167. switch (fill_rule) {
  168. case CSS::FillRule::Nonzero:
  169. return FillRule::Nonzero;
  170. case CSS::FillRule::Evenodd:
  171. return FillRule::Evenodd;
  172. default:
  173. VERIFY_NOT_REACHED();
  174. }
  175. }
  176. Optional<FillRule> SVGGraphicsElement::fill_rule() const
  177. {
  178. if (!layout_node())
  179. return {};
  180. return to_svg_fill_rule(layout_node()->computed_values().fill_rule());
  181. }
  182. Optional<ClipRule> SVGGraphicsElement::clip_rule() const
  183. {
  184. if (!layout_node())
  185. return {};
  186. return to_svg_fill_rule(layout_node()->computed_values().clip_rule());
  187. }
  188. Optional<Gfx::Color> SVGGraphicsElement::fill_color() const
  189. {
  190. if (!layout_node())
  191. return {};
  192. // FIXME: In the working-draft spec, `fill` is intended to be a shorthand, with `fill-color`
  193. // being what we actually want to use. But that's not final or widely supported yet.
  194. return layout_node()->computed_values().fill().map([&](auto& paint) -> Gfx::Color {
  195. if (!paint.is_color())
  196. return Color::Black;
  197. return paint.as_color();
  198. });
  199. }
  200. Optional<Gfx::Color> SVGGraphicsElement::stroke_color() const
  201. {
  202. if (!layout_node())
  203. return {};
  204. // FIXME: In the working-draft spec, `stroke` is intended to be a shorthand, with `stroke-color`
  205. // being what we actually want to use. But that's not final or widely supported yet.
  206. return layout_node()->computed_values().stroke().map([](auto& paint) -> Gfx::Color {
  207. if (!paint.is_color())
  208. return Color::Black;
  209. return paint.as_color();
  210. });
  211. }
  212. Optional<float> SVGGraphicsElement::fill_opacity() const
  213. {
  214. if (!layout_node())
  215. return {};
  216. return layout_node()->computed_values().fill_opacity();
  217. }
  218. Optional<CSS::StrokeLinecap> SVGGraphicsElement::stroke_linecap() const
  219. {
  220. if (!layout_node())
  221. return {};
  222. return layout_node()->computed_values().stroke_linecap();
  223. }
  224. Optional<CSS::StrokeLinejoin> SVGGraphicsElement::stroke_linejoin() const
  225. {
  226. if (!layout_node())
  227. return {};
  228. return layout_node()->computed_values().stroke_linejoin();
  229. }
  230. Optional<CSS::NumberOrCalculated> SVGGraphicsElement::stroke_miterlimit() const
  231. {
  232. if (!layout_node())
  233. return {};
  234. return layout_node()->computed_values().stroke_miterlimit();
  235. }
  236. Optional<float> SVGGraphicsElement::stroke_opacity() const
  237. {
  238. if (!layout_node())
  239. return {};
  240. return layout_node()->computed_values().stroke_opacity();
  241. }
  242. float SVGGraphicsElement::resolve_relative_to_viewport_size(CSS::LengthPercentage const& length_percentage) const
  243. {
  244. // FIXME: Converting to pixels isn't really correct - values should be in "user units"
  245. // https://svgwg.org/svg2-draft/coords.html#TermUserUnits
  246. // Resolved relative to the "Scaled viewport size": https://www.w3.org/TR/2017/WD-fill-stroke-3-20170413/#scaled-viewport-size
  247. // FIXME: This isn't right, but it's something.
  248. CSSPixels viewport_width = 0;
  249. CSSPixels viewport_height = 0;
  250. if (auto* svg_svg_element = shadow_including_first_ancestor_of_type<SVGSVGElement>()) {
  251. if (auto svg_svg_layout_node = svg_svg_element->layout_node()) {
  252. viewport_width = svg_svg_layout_node->computed_values().width().to_px(*svg_svg_layout_node, 0);
  253. viewport_height = svg_svg_layout_node->computed_values().height().to_px(*svg_svg_layout_node, 0);
  254. }
  255. }
  256. auto scaled_viewport_size = (viewport_width + viewport_height) * CSSPixels(0.5);
  257. return length_percentage.to_px(*layout_node(), scaled_viewport_size).to_double();
  258. }
  259. Optional<float> SVGGraphicsElement::stroke_dashoffset() const
  260. {
  261. if (!layout_node())
  262. return {};
  263. return resolve_relative_to_viewport_size(layout_node()->computed_values().stroke_dashoffset());
  264. }
  265. Optional<float> SVGGraphicsElement::stroke_width() const
  266. {
  267. if (!layout_node())
  268. return {};
  269. return resolve_relative_to_viewport_size(layout_node()->computed_values().stroke_width());
  270. }
  271. // https://svgwg.org/svg2-draft/types.html#__svg__SVGGraphicsElement__getBBox
  272. GC::Ref<Geometry::DOMRect> SVGGraphicsElement::get_b_box(Optional<SVGBoundingBoxOptions>)
  273. {
  274. // FIXME: It should be possible to compute this without layout updates. The bounding box is within the
  275. // SVG coordinate space (before any viewbox or other transformations), so it should be possible to
  276. // calculate this from SVG geometry without a full layout tree (at least for simple cases).
  277. // See: https://svgwg.org/svg2-draft/coords.html#BoundingBoxes
  278. const_cast<DOM::Document&>(document()).update_layout();
  279. if (!layout_node())
  280. return Geometry::DOMRect::create(realm());
  281. // Invert the SVG -> screen space transform.
  282. auto owner_svg_element = this->owner_svg_element();
  283. if (!owner_svg_element)
  284. return Geometry::DOMRect::create(realm());
  285. auto svg_element_rect = owner_svg_element->paintable_box()->absolute_rect();
  286. auto inverse_transform = static_cast<Painting::SVGGraphicsPaintable&>(*paintable_box()).computed_transforms().svg_to_css_pixels_transform().inverse();
  287. auto translated_rect = paintable_box()->absolute_rect().to_type<float>().translated(-svg_element_rect.location().to_type<float>());
  288. if (inverse_transform.has_value())
  289. translated_rect = inverse_transform->map(translated_rect);
  290. return Geometry::DOMRect::create(realm(), translated_rect);
  291. }
  292. GC::Ref<SVGAnimatedTransformList> SVGGraphicsElement::transform() const
  293. {
  294. dbgln("(STUBBED) SVGGraphicsElement::transform(). Called on: {}", debug_description());
  295. auto base_val = SVGTransformList::create(realm());
  296. auto anim_val = SVGTransformList::create(realm());
  297. return SVGAnimatedTransformList::create(realm(), base_val, anim_val);
  298. }
  299. GC::Ptr<Geometry::DOMMatrix> SVGGraphicsElement::get_screen_ctm()
  300. {
  301. dbgln("(STUBBED) SVGGraphicsElement::get_screen_ctm(). Called on: {}", debug_description());
  302. return Geometry::DOMMatrix::create(realm());
  303. }
  304. }